babylon.no-module.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854
  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. * @param options defines an option object to be sent to the requestFullscreen function
  12686. */
  12687. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12688. if (this.isFullscreen) {
  12689. BABYLON.Tools.ExitFullscreen();
  12690. }
  12691. else {
  12692. this._pointerLockRequested = requestPointerLock;
  12693. if (this._renderingCanvas) {
  12694. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12695. }
  12696. }
  12697. };
  12698. /**
  12699. * Clear the current render buffer or the current render target (if any is set up)
  12700. * @param color defines the color to use
  12701. * @param backBuffer defines if the back buffer must be cleared
  12702. * @param depth defines if the depth buffer must be cleared
  12703. * @param stencil defines if the stencil buffer must be cleared
  12704. */
  12705. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12706. if (stencil === void 0) { stencil = false; }
  12707. this.applyStates();
  12708. var mode = 0;
  12709. if (backBuffer && color) {
  12710. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12711. mode |= this._gl.COLOR_BUFFER_BIT;
  12712. }
  12713. if (depth) {
  12714. this._gl.clearDepth(1.0);
  12715. mode |= this._gl.DEPTH_BUFFER_BIT;
  12716. }
  12717. if (stencil) {
  12718. this._gl.clearStencil(0);
  12719. mode |= this._gl.STENCIL_BUFFER_BIT;
  12720. }
  12721. this._gl.clear(mode);
  12722. };
  12723. /**
  12724. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12725. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12726. * @param y defines the y-coordinate of the corner of the clear rectangle
  12727. * @param width defines the width of the clear rectangle
  12728. * @param height defines the height of the clear rectangle
  12729. * @param clearColor defines the clear color
  12730. */
  12731. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12732. var gl = this._gl;
  12733. // Save state
  12734. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12735. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12736. // Change state
  12737. gl.enable(gl.SCISSOR_TEST);
  12738. gl.scissor(x, y, width, height);
  12739. // Clear
  12740. this.clear(clearColor, true, true, true);
  12741. // Restore state
  12742. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12743. if (curScissor === true) {
  12744. gl.enable(gl.SCISSOR_TEST);
  12745. }
  12746. else {
  12747. gl.disable(gl.SCISSOR_TEST);
  12748. }
  12749. };
  12750. /** @hidden */
  12751. Engine.prototype._viewport = function (x, y, width, height) {
  12752. if (x !== this._viewportCached.x ||
  12753. y !== this._viewportCached.y ||
  12754. width !== this._viewportCached.z ||
  12755. height !== this._viewportCached.w) {
  12756. this._viewportCached.x = x;
  12757. this._viewportCached.y = y;
  12758. this._viewportCached.z = width;
  12759. this._viewportCached.w = height;
  12760. this._gl.viewport(x, y, width, height);
  12761. }
  12762. };
  12763. /**
  12764. * Set the WebGL's viewport
  12765. * @param viewport defines the viewport element to be used
  12766. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12767. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12768. */
  12769. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12770. var width = requiredWidth || this.getRenderWidth();
  12771. var height = requiredHeight || this.getRenderHeight();
  12772. var x = viewport.x || 0;
  12773. var y = viewport.y || 0;
  12774. this._cachedViewport = viewport;
  12775. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12776. };
  12777. /**
  12778. * Directly set the WebGL Viewport
  12779. * @param x defines the x coordinate of the viewport (in screen space)
  12780. * @param y defines the y coordinate of the viewport (in screen space)
  12781. * @param width defines the width of the viewport (in screen space)
  12782. * @param height defines the height of the viewport (in screen space)
  12783. * @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
  12784. */
  12785. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12786. var currentViewport = this._cachedViewport;
  12787. this._cachedViewport = null;
  12788. this._viewport(x, y, width, height);
  12789. return currentViewport;
  12790. };
  12791. /**
  12792. * Begin a new frame
  12793. */
  12794. Engine.prototype.beginFrame = function () {
  12795. this.onBeginFrameObservable.notifyObservers(this);
  12796. this._measureFps();
  12797. };
  12798. /**
  12799. * Enf the current frame
  12800. */
  12801. Engine.prototype.endFrame = function () {
  12802. // Force a flush in case we are using a bad OS.
  12803. if (this._badOS) {
  12804. this.flushFramebuffer();
  12805. }
  12806. // Submit frame to the vr device, if enabled
  12807. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12808. // TODO: We should only submit the frame if we read frameData successfully.
  12809. this._vrDisplay.submitFrame();
  12810. }
  12811. this.onEndFrameObservable.notifyObservers(this);
  12812. };
  12813. /**
  12814. * Resize the view according to the canvas' size
  12815. */
  12816. Engine.prototype.resize = function () {
  12817. // We're not resizing the size of the canvas while in VR mode & presenting
  12818. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12819. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12820. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12821. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12822. }
  12823. };
  12824. /**
  12825. * Force a specific size of the canvas
  12826. * @param width defines the new canvas' width
  12827. * @param height defines the new canvas' height
  12828. */
  12829. Engine.prototype.setSize = function (width, height) {
  12830. if (!this._renderingCanvas) {
  12831. return;
  12832. }
  12833. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12834. return;
  12835. }
  12836. this._renderingCanvas.width = width;
  12837. this._renderingCanvas.height = height;
  12838. for (var index = 0; index < this.scenes.length; index++) {
  12839. var scene = this.scenes[index];
  12840. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12841. var cam = scene.cameras[camIndex];
  12842. cam._currentRenderId = 0;
  12843. }
  12844. }
  12845. if (this.onResizeObservable.hasObservers) {
  12846. this.onResizeObservable.notifyObservers(this);
  12847. }
  12848. };
  12849. // WebVR functions
  12850. /**
  12851. * Gets a boolean indicating if a webVR device was detected
  12852. * @returns true if a webVR device was detected
  12853. */
  12854. Engine.prototype.isVRDevicePresent = function () {
  12855. return !!this._vrDisplay;
  12856. };
  12857. /**
  12858. * Gets the current webVR device
  12859. * @returns the current webVR device (or null)
  12860. */
  12861. Engine.prototype.getVRDevice = function () {
  12862. return this._vrDisplay;
  12863. };
  12864. /**
  12865. * Initializes a webVR display and starts listening to display change events
  12866. * The onVRDisplayChangedObservable will be notified upon these changes
  12867. * @returns The onVRDisplayChangedObservable
  12868. */
  12869. Engine.prototype.initWebVR = function () {
  12870. this.initWebVRAsync();
  12871. return this.onVRDisplayChangedObservable;
  12872. };
  12873. /**
  12874. * Initializes a webVR display and starts listening to display change events
  12875. * The onVRDisplayChangedObservable will be notified upon these changes
  12876. * @returns A promise containing a VRDisplay and if vr is supported
  12877. */
  12878. Engine.prototype.initWebVRAsync = function () {
  12879. var _this = this;
  12880. var notifyObservers = function () {
  12881. var eventArgs = {
  12882. vrDisplay: _this._vrDisplay,
  12883. vrSupported: _this._vrSupported
  12884. };
  12885. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12886. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12887. };
  12888. if (!this._onVrDisplayConnect) {
  12889. this._onVrDisplayConnect = function (event) {
  12890. _this._vrDisplay = event.display;
  12891. notifyObservers();
  12892. };
  12893. this._onVrDisplayDisconnect = function () {
  12894. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12895. _this._vrDisplay = undefined;
  12896. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12897. notifyObservers();
  12898. };
  12899. this._onVrDisplayPresentChange = function () {
  12900. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12901. };
  12902. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12903. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12904. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12905. }
  12906. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12907. this._webVRInitPromise.then(notifyObservers);
  12908. return this._webVRInitPromise;
  12909. };
  12910. /**
  12911. * Call this function to switch to webVR mode
  12912. * Will do nothing if webVR is not supported or if there is no webVR device
  12913. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12914. */
  12915. Engine.prototype.enableVR = function () {
  12916. var _this = this;
  12917. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12918. var onResolved = function () {
  12919. _this.onVRRequestPresentComplete.notifyObservers(true);
  12920. _this._onVRFullScreenTriggered();
  12921. };
  12922. var onRejected = function () {
  12923. _this.onVRRequestPresentComplete.notifyObservers(false);
  12924. };
  12925. this.onVRRequestPresentStart.notifyObservers(this);
  12926. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12927. }
  12928. };
  12929. /**
  12930. * Call this function to leave webVR mode
  12931. * Will do nothing if webVR is not supported or if there is no webVR device
  12932. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12933. */
  12934. Engine.prototype.disableVR = function () {
  12935. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12936. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12937. }
  12938. };
  12939. Engine.prototype._getVRDisplaysAsync = function () {
  12940. var _this = this;
  12941. return new Promise(function (res, rej) {
  12942. if (navigator.getVRDisplays) {
  12943. navigator.getVRDisplays().then(function (devices) {
  12944. _this._vrSupported = true;
  12945. // note that devices may actually be an empty array. This is fine;
  12946. // we expect this._vrDisplay to be undefined in this case.
  12947. _this._vrDisplay = devices[0];
  12948. res({
  12949. vrDisplay: _this._vrDisplay,
  12950. vrSupported: _this._vrSupported
  12951. });
  12952. });
  12953. }
  12954. else {
  12955. _this._vrDisplay = undefined;
  12956. _this._vrSupported = false;
  12957. res({
  12958. vrDisplay: _this._vrDisplay,
  12959. vrSupported: _this._vrSupported
  12960. });
  12961. }
  12962. });
  12963. };
  12964. /**
  12965. * Binds the frame buffer to the specified texture.
  12966. * @param texture The texture to render to or null for the default canvas
  12967. * @param faceIndex The face of the texture to render to in case of cube texture
  12968. * @param requiredWidth The width of the target to render to
  12969. * @param requiredHeight The height of the target to render to
  12970. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12971. * @param depthStencilTexture The depth stencil texture to use to render
  12972. * @param lodLevel defines le lod level to bind to the frame buffer
  12973. */
  12974. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12975. if (lodLevel === void 0) { lodLevel = 0; }
  12976. if (this._currentRenderTarget) {
  12977. this.unBindFramebuffer(this._currentRenderTarget);
  12978. }
  12979. this._currentRenderTarget = texture;
  12980. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12981. var gl = this._gl;
  12982. if (texture.isCube) {
  12983. if (faceIndex === undefined) {
  12984. faceIndex = 0;
  12985. }
  12986. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12987. if (depthStencilTexture) {
  12988. if (depthStencilTexture._generateStencilBuffer) {
  12989. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12990. }
  12991. else {
  12992. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12993. }
  12994. }
  12995. }
  12996. if (this._cachedViewport && !forceFullscreenViewport) {
  12997. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12998. }
  12999. else {
  13000. if (!requiredWidth) {
  13001. requiredWidth = texture.width;
  13002. if (lodLevel) {
  13003. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13004. }
  13005. }
  13006. if (!requiredHeight) {
  13007. requiredHeight = texture.height;
  13008. if (lodLevel) {
  13009. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13010. }
  13011. }
  13012. this._viewport(0, 0, requiredWidth, requiredHeight);
  13013. }
  13014. this.wipeCaches();
  13015. };
  13016. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13017. if (this._currentFramebuffer !== framebuffer) {
  13018. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13019. this._currentFramebuffer = framebuffer;
  13020. }
  13021. };
  13022. /**
  13023. * Unbind the current render target texture from the webGL context
  13024. * @param texture defines the render target texture to unbind
  13025. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13026. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13027. */
  13028. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13029. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13030. this._currentRenderTarget = null;
  13031. // If MSAA, we need to bitblt back to main texture
  13032. var gl = this._gl;
  13033. if (texture._MSAAFramebuffer) {
  13034. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13035. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13036. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13037. }
  13038. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13039. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13040. gl.generateMipmap(gl.TEXTURE_2D);
  13041. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13042. }
  13043. if (onBeforeUnbind) {
  13044. if (texture._MSAAFramebuffer) {
  13045. // Bind the correct framebuffer
  13046. this.bindUnboundFramebuffer(texture._framebuffer);
  13047. }
  13048. onBeforeUnbind();
  13049. }
  13050. this.bindUnboundFramebuffer(null);
  13051. };
  13052. /**
  13053. * Unbind a list of render target textures from the webGL context
  13054. * This is used only when drawBuffer extension or webGL2 are active
  13055. * @param textures defines the render target textures to unbind
  13056. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13057. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13058. */
  13059. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13060. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13061. this._currentRenderTarget = null;
  13062. // If MSAA, we need to bitblt back to main texture
  13063. var gl = this._gl;
  13064. if (textures[0]._MSAAFramebuffer) {
  13065. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13066. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13067. var attachments = textures[0]._attachments;
  13068. if (!attachments) {
  13069. attachments = new Array(textures.length);
  13070. textures[0]._attachments = attachments;
  13071. }
  13072. for (var i = 0; i < textures.length; i++) {
  13073. var texture = textures[i];
  13074. for (var j = 0; j < attachments.length; j++) {
  13075. attachments[j] = gl.NONE;
  13076. }
  13077. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13078. gl.readBuffer(attachments[i]);
  13079. gl.drawBuffers(attachments);
  13080. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13081. }
  13082. for (var i = 0; i < attachments.length; i++) {
  13083. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13084. }
  13085. gl.drawBuffers(attachments);
  13086. }
  13087. for (var i = 0; i < textures.length; i++) {
  13088. var texture = textures[i];
  13089. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13090. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13091. gl.generateMipmap(gl.TEXTURE_2D);
  13092. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13093. }
  13094. }
  13095. if (onBeforeUnbind) {
  13096. if (textures[0]._MSAAFramebuffer) {
  13097. // Bind the correct framebuffer
  13098. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13099. }
  13100. onBeforeUnbind();
  13101. }
  13102. this.bindUnboundFramebuffer(null);
  13103. };
  13104. /**
  13105. * Force the mipmap generation for the given render target texture
  13106. * @param texture defines the render target texture to use
  13107. */
  13108. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13109. if (texture.generateMipMaps) {
  13110. var gl = this._gl;
  13111. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13112. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13113. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13114. }
  13115. };
  13116. /**
  13117. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13118. */
  13119. Engine.prototype.flushFramebuffer = function () {
  13120. this._gl.flush();
  13121. };
  13122. /**
  13123. * Unbind the current render target and bind the default framebuffer
  13124. */
  13125. Engine.prototype.restoreDefaultFramebuffer = function () {
  13126. if (this._currentRenderTarget) {
  13127. this.unBindFramebuffer(this._currentRenderTarget);
  13128. }
  13129. else {
  13130. this.bindUnboundFramebuffer(null);
  13131. }
  13132. if (this._cachedViewport) {
  13133. this.setViewport(this._cachedViewport);
  13134. }
  13135. this.wipeCaches();
  13136. };
  13137. // UBOs
  13138. /**
  13139. * Create an uniform buffer
  13140. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13141. * @param elements defines the content of the uniform buffer
  13142. * @returns the webGL uniform buffer
  13143. */
  13144. Engine.prototype.createUniformBuffer = function (elements) {
  13145. var ubo = this._gl.createBuffer();
  13146. if (!ubo) {
  13147. throw new Error("Unable to create uniform buffer");
  13148. }
  13149. this.bindUniformBuffer(ubo);
  13150. if (elements instanceof Float32Array) {
  13151. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13152. }
  13153. else {
  13154. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13155. }
  13156. this.bindUniformBuffer(null);
  13157. ubo.references = 1;
  13158. return ubo;
  13159. };
  13160. /**
  13161. * Create a dynamic uniform buffer
  13162. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13163. * @param elements defines the content of the uniform buffer
  13164. * @returns the webGL uniform buffer
  13165. */
  13166. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13167. var ubo = this._gl.createBuffer();
  13168. if (!ubo) {
  13169. throw new Error("Unable to create dynamic uniform buffer");
  13170. }
  13171. this.bindUniformBuffer(ubo);
  13172. if (elements instanceof Float32Array) {
  13173. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13174. }
  13175. else {
  13176. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13177. }
  13178. this.bindUniformBuffer(null);
  13179. ubo.references = 1;
  13180. return ubo;
  13181. };
  13182. /**
  13183. * Update an existing uniform buffer
  13184. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13185. * @param uniformBuffer defines the target uniform buffer
  13186. * @param elements defines the content to update
  13187. * @param offset defines the offset in the uniform buffer where update should start
  13188. * @param count defines the size of the data to update
  13189. */
  13190. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13191. this.bindUniformBuffer(uniformBuffer);
  13192. if (offset === undefined) {
  13193. offset = 0;
  13194. }
  13195. if (count === undefined) {
  13196. if (elements instanceof Float32Array) {
  13197. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13198. }
  13199. else {
  13200. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13201. }
  13202. }
  13203. else {
  13204. if (elements instanceof Float32Array) {
  13205. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13206. }
  13207. else {
  13208. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13209. }
  13210. }
  13211. this.bindUniformBuffer(null);
  13212. };
  13213. // VBOs
  13214. Engine.prototype._resetVertexBufferBinding = function () {
  13215. this.bindArrayBuffer(null);
  13216. this._cachedVertexBuffers = null;
  13217. };
  13218. /**
  13219. * Creates a vertex buffer
  13220. * @param data the data for the vertex buffer
  13221. * @returns the new WebGL static buffer
  13222. */
  13223. Engine.prototype.createVertexBuffer = function (data) {
  13224. var vbo = this._gl.createBuffer();
  13225. if (!vbo) {
  13226. throw new Error("Unable to create vertex buffer");
  13227. }
  13228. this.bindArrayBuffer(vbo);
  13229. if (data instanceof Array) {
  13230. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13231. }
  13232. else {
  13233. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13234. }
  13235. this._resetVertexBufferBinding();
  13236. vbo.references = 1;
  13237. return vbo;
  13238. };
  13239. /**
  13240. * Creates a dynamic vertex buffer
  13241. * @param data the data for the dynamic vertex buffer
  13242. * @returns the new WebGL dynamic buffer
  13243. */
  13244. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13245. var vbo = this._gl.createBuffer();
  13246. if (!vbo) {
  13247. throw new Error("Unable to create dynamic vertex buffer");
  13248. }
  13249. this.bindArrayBuffer(vbo);
  13250. if (data instanceof Array) {
  13251. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13252. }
  13253. else {
  13254. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13255. }
  13256. this._resetVertexBufferBinding();
  13257. vbo.references = 1;
  13258. return vbo;
  13259. };
  13260. /**
  13261. * Update a dynamic index buffer
  13262. * @param indexBuffer defines the target index buffer
  13263. * @param indices defines the data to update
  13264. * @param offset defines the offset in the target index buffer where update should start
  13265. */
  13266. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13267. if (offset === void 0) { offset = 0; }
  13268. // Force cache update
  13269. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13270. this.bindIndexBuffer(indexBuffer);
  13271. var arrayBuffer;
  13272. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13273. arrayBuffer = indices;
  13274. }
  13275. else {
  13276. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13277. }
  13278. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13279. this._resetIndexBufferBinding();
  13280. };
  13281. /**
  13282. * Updates a dynamic vertex buffer.
  13283. * @param vertexBuffer the vertex buffer to update
  13284. * @param data the data used to update the vertex buffer
  13285. * @param byteOffset the byte offset of the data
  13286. * @param byteLength the byte length of the data
  13287. */
  13288. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13289. this.bindArrayBuffer(vertexBuffer);
  13290. if (byteOffset === undefined) {
  13291. byteOffset = 0;
  13292. }
  13293. if (byteLength === undefined) {
  13294. if (data instanceof Array) {
  13295. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13296. }
  13297. else {
  13298. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13299. }
  13300. }
  13301. else {
  13302. if (data instanceof Array) {
  13303. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13304. }
  13305. else {
  13306. if (data instanceof ArrayBuffer) {
  13307. data = new Uint8Array(data, byteOffset, byteLength);
  13308. }
  13309. else {
  13310. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13311. }
  13312. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13313. }
  13314. }
  13315. this._resetVertexBufferBinding();
  13316. };
  13317. Engine.prototype._resetIndexBufferBinding = function () {
  13318. this.bindIndexBuffer(null);
  13319. this._cachedIndexBuffer = null;
  13320. };
  13321. /**
  13322. * Creates a new index buffer
  13323. * @param indices defines the content of the index buffer
  13324. * @param updatable defines if the index buffer must be updatable
  13325. * @returns a new webGL buffer
  13326. */
  13327. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13328. var vbo = this._gl.createBuffer();
  13329. if (!vbo) {
  13330. throw new Error("Unable to create index buffer");
  13331. }
  13332. this.bindIndexBuffer(vbo);
  13333. // Check for 32 bits indices
  13334. var arrayBuffer;
  13335. var need32Bits = false;
  13336. if (indices instanceof Uint16Array) {
  13337. arrayBuffer = indices;
  13338. }
  13339. else {
  13340. //check 32 bit support
  13341. if (this._caps.uintIndices) {
  13342. if (indices instanceof Uint32Array) {
  13343. arrayBuffer = indices;
  13344. need32Bits = true;
  13345. }
  13346. else {
  13347. //number[] or Int32Array, check if 32 bit is necessary
  13348. for (var index = 0; index < indices.length; index++) {
  13349. if (indices[index] > 65535) {
  13350. need32Bits = true;
  13351. break;
  13352. }
  13353. }
  13354. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13355. }
  13356. }
  13357. else {
  13358. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13359. arrayBuffer = new Uint16Array(indices);
  13360. }
  13361. }
  13362. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13363. this._resetIndexBufferBinding();
  13364. vbo.references = 1;
  13365. vbo.is32Bits = need32Bits;
  13366. return vbo;
  13367. };
  13368. /**
  13369. * Bind a webGL buffer to the webGL context
  13370. * @param buffer defines the buffer to bind
  13371. */
  13372. Engine.prototype.bindArrayBuffer = function (buffer) {
  13373. if (!this._vaoRecordInProgress) {
  13374. this._unbindVertexArrayObject();
  13375. }
  13376. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13377. };
  13378. /**
  13379. * Bind an uniform buffer to the current webGL context
  13380. * @param buffer defines the buffer to bind
  13381. */
  13382. Engine.prototype.bindUniformBuffer = function (buffer) {
  13383. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13384. };
  13385. /**
  13386. * Bind a buffer to the current webGL context at a given location
  13387. * @param buffer defines the buffer to bind
  13388. * @param location defines the index where to bind the buffer
  13389. */
  13390. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13391. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13392. };
  13393. /**
  13394. * Bind a specific block at a given index in a specific shader program
  13395. * @param shaderProgram defines the shader program
  13396. * @param blockName defines the block name
  13397. * @param index defines the index where to bind the block
  13398. */
  13399. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13400. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13401. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13402. };
  13403. ;
  13404. Engine.prototype.bindIndexBuffer = function (buffer) {
  13405. if (!this._vaoRecordInProgress) {
  13406. this._unbindVertexArrayObject();
  13407. }
  13408. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13409. };
  13410. Engine.prototype.bindBuffer = function (buffer, target) {
  13411. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13412. this._gl.bindBuffer(target, buffer);
  13413. this._currentBoundBuffer[target] = buffer;
  13414. }
  13415. };
  13416. /**
  13417. * update the bound buffer with the given data
  13418. * @param data defines the data to update
  13419. */
  13420. Engine.prototype.updateArrayBuffer = function (data) {
  13421. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13422. };
  13423. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13424. var pointer = this._currentBufferPointers[indx];
  13425. var changed = false;
  13426. if (!pointer.active) {
  13427. changed = true;
  13428. pointer.active = true;
  13429. pointer.index = indx;
  13430. pointer.size = size;
  13431. pointer.type = type;
  13432. pointer.normalized = normalized;
  13433. pointer.stride = stride;
  13434. pointer.offset = offset;
  13435. pointer.buffer = buffer;
  13436. }
  13437. else {
  13438. if (pointer.buffer !== buffer) {
  13439. pointer.buffer = buffer;
  13440. changed = true;
  13441. }
  13442. if (pointer.size !== size) {
  13443. pointer.size = size;
  13444. changed = true;
  13445. }
  13446. if (pointer.type !== type) {
  13447. pointer.type = type;
  13448. changed = true;
  13449. }
  13450. if (pointer.normalized !== normalized) {
  13451. pointer.normalized = normalized;
  13452. changed = true;
  13453. }
  13454. if (pointer.stride !== stride) {
  13455. pointer.stride = stride;
  13456. changed = true;
  13457. }
  13458. if (pointer.offset !== offset) {
  13459. pointer.offset = offset;
  13460. changed = true;
  13461. }
  13462. }
  13463. if (changed || this._vaoRecordInProgress) {
  13464. this.bindArrayBuffer(buffer);
  13465. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13466. }
  13467. };
  13468. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13469. if (indexBuffer == null) {
  13470. return;
  13471. }
  13472. if (this._cachedIndexBuffer !== indexBuffer) {
  13473. this._cachedIndexBuffer = indexBuffer;
  13474. this.bindIndexBuffer(indexBuffer);
  13475. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13476. }
  13477. };
  13478. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13479. var attributes = effect.getAttributesNames();
  13480. if (!this._vaoRecordInProgress) {
  13481. this._unbindVertexArrayObject();
  13482. }
  13483. this.unbindAllAttributes();
  13484. for (var index = 0; index < attributes.length; index++) {
  13485. var order = effect.getAttributeLocation(index);
  13486. if (order >= 0) {
  13487. var vertexBuffer = vertexBuffers[attributes[index]];
  13488. if (!vertexBuffer) {
  13489. continue;
  13490. }
  13491. this._gl.enableVertexAttribArray(order);
  13492. if (!this._vaoRecordInProgress) {
  13493. this._vertexAttribArraysEnabled[order] = true;
  13494. }
  13495. var buffer = vertexBuffer.getBuffer();
  13496. if (buffer) {
  13497. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13498. if (vertexBuffer.getIsInstanced()) {
  13499. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13500. if (!this._vaoRecordInProgress) {
  13501. this._currentInstanceLocations.push(order);
  13502. this._currentInstanceBuffers.push(buffer);
  13503. }
  13504. }
  13505. }
  13506. }
  13507. }
  13508. };
  13509. /**
  13510. * Records a vertex array object
  13511. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13512. * @param vertexBuffers defines the list of vertex buffers to store
  13513. * @param indexBuffer defines the index buffer to store
  13514. * @param effect defines the effect to store
  13515. * @returns the new vertex array object
  13516. */
  13517. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13518. var vao = this._gl.createVertexArray();
  13519. this._vaoRecordInProgress = true;
  13520. this._gl.bindVertexArray(vao);
  13521. this._mustWipeVertexAttributes = true;
  13522. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13523. this.bindIndexBuffer(indexBuffer);
  13524. this._vaoRecordInProgress = false;
  13525. this._gl.bindVertexArray(null);
  13526. return vao;
  13527. };
  13528. /**
  13529. * Bind a specific vertex array object
  13530. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13531. * @param vertexArrayObject defines the vertex array object to bind
  13532. * @param indexBuffer defines the index buffer to bind
  13533. */
  13534. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13535. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13536. this._cachedVertexArrayObject = vertexArrayObject;
  13537. this._gl.bindVertexArray(vertexArrayObject);
  13538. this._cachedVertexBuffers = null;
  13539. this._cachedIndexBuffer = null;
  13540. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13541. this._mustWipeVertexAttributes = true;
  13542. }
  13543. };
  13544. /**
  13545. * Bind webGl buffers directly to the webGL context
  13546. * @param vertexBuffer defines the vertex buffer to bind
  13547. * @param indexBuffer defines the index buffer to bind
  13548. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13549. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13550. * @param effect defines the effect associated with the vertex buffer
  13551. */
  13552. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13553. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13554. this._cachedVertexBuffers = vertexBuffer;
  13555. this._cachedEffectForVertexBuffers = effect;
  13556. var attributesCount = effect.getAttributesCount();
  13557. this._unbindVertexArrayObject();
  13558. this.unbindAllAttributes();
  13559. var offset = 0;
  13560. for (var index = 0; index < attributesCount; index++) {
  13561. if (index < vertexDeclaration.length) {
  13562. var order = effect.getAttributeLocation(index);
  13563. if (order >= 0) {
  13564. this._gl.enableVertexAttribArray(order);
  13565. this._vertexAttribArraysEnabled[order] = true;
  13566. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13567. }
  13568. offset += vertexDeclaration[index] * 4;
  13569. }
  13570. }
  13571. }
  13572. this._bindIndexBufferWithCache(indexBuffer);
  13573. };
  13574. Engine.prototype._unbindVertexArrayObject = function () {
  13575. if (!this._cachedVertexArrayObject) {
  13576. return;
  13577. }
  13578. this._cachedVertexArrayObject = null;
  13579. this._gl.bindVertexArray(null);
  13580. };
  13581. /**
  13582. * Bind a list of vertex buffers to the webGL context
  13583. * @param vertexBuffers defines the list of vertex buffers to bind
  13584. * @param indexBuffer defines the index buffer to bind
  13585. * @param effect defines the effect associated with the vertex buffers
  13586. */
  13587. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13588. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13589. this._cachedVertexBuffers = vertexBuffers;
  13590. this._cachedEffectForVertexBuffers = effect;
  13591. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13592. }
  13593. this._bindIndexBufferWithCache(indexBuffer);
  13594. };
  13595. /**
  13596. * Unbind all instance attributes
  13597. */
  13598. Engine.prototype.unbindInstanceAttributes = function () {
  13599. var boundBuffer;
  13600. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13601. var instancesBuffer = this._currentInstanceBuffers[i];
  13602. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13603. boundBuffer = instancesBuffer;
  13604. this.bindArrayBuffer(instancesBuffer);
  13605. }
  13606. var offsetLocation = this._currentInstanceLocations[i];
  13607. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13608. }
  13609. this._currentInstanceBuffers.length = 0;
  13610. this._currentInstanceLocations.length = 0;
  13611. };
  13612. /**
  13613. * Release and free the memory of a vertex array object
  13614. * @param vao defines the vertex array object to delete
  13615. */
  13616. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13617. this._gl.deleteVertexArray(vao);
  13618. };
  13619. /** @hidden */
  13620. Engine.prototype._releaseBuffer = function (buffer) {
  13621. buffer.references--;
  13622. if (buffer.references === 0) {
  13623. this._gl.deleteBuffer(buffer);
  13624. return true;
  13625. }
  13626. return false;
  13627. };
  13628. /**
  13629. * Creates a webGL buffer to use with instanciation
  13630. * @param capacity defines the size of the buffer
  13631. * @returns the webGL buffer
  13632. */
  13633. Engine.prototype.createInstancesBuffer = function (capacity) {
  13634. var buffer = this._gl.createBuffer();
  13635. if (!buffer) {
  13636. throw new Error("Unable to create instance buffer");
  13637. }
  13638. buffer.capacity = capacity;
  13639. this.bindArrayBuffer(buffer);
  13640. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13641. return buffer;
  13642. };
  13643. /**
  13644. * Delete a webGL buffer used with instanciation
  13645. * @param buffer defines the webGL buffer to delete
  13646. */
  13647. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13648. this._gl.deleteBuffer(buffer);
  13649. };
  13650. /**
  13651. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13652. * @param instancesBuffer defines the webGL buffer to update and bind
  13653. * @param data defines the data to store in the buffer
  13654. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13655. */
  13656. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13657. this.bindArrayBuffer(instancesBuffer);
  13658. if (data) {
  13659. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13660. }
  13661. if (offsetLocations[0].index !== undefined) {
  13662. var stride = 0;
  13663. for (var i = 0; i < offsetLocations.length; i++) {
  13664. var ai = offsetLocations[i];
  13665. stride += ai.attributeSize * 4;
  13666. }
  13667. for (var i = 0; i < offsetLocations.length; i++) {
  13668. var ai = offsetLocations[i];
  13669. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13670. this._gl.enableVertexAttribArray(ai.index);
  13671. this._vertexAttribArraysEnabled[ai.index] = true;
  13672. }
  13673. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13674. this._gl.vertexAttribDivisor(ai.index, 1);
  13675. this._currentInstanceLocations.push(ai.index);
  13676. this._currentInstanceBuffers.push(instancesBuffer);
  13677. }
  13678. }
  13679. else {
  13680. for (var index = 0; index < 4; index++) {
  13681. var offsetLocation = offsetLocations[index];
  13682. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13683. this._gl.enableVertexAttribArray(offsetLocation);
  13684. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13685. }
  13686. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13687. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13688. this._currentInstanceLocations.push(offsetLocation);
  13689. this._currentInstanceBuffers.push(instancesBuffer);
  13690. }
  13691. }
  13692. };
  13693. /**
  13694. * Apply all cached states (depth, culling, stencil and alpha)
  13695. */
  13696. Engine.prototype.applyStates = function () {
  13697. this._depthCullingState.apply(this._gl);
  13698. this._stencilState.apply(this._gl);
  13699. this._alphaState.apply(this._gl);
  13700. };
  13701. /**
  13702. * Send a draw order
  13703. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13704. * @param indexStart defines the starting index
  13705. * @param indexCount defines the number of index to draw
  13706. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13707. */
  13708. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13709. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13710. };
  13711. /**
  13712. * Draw a list of points
  13713. * @param verticesStart defines the index of first vertex to draw
  13714. * @param verticesCount defines the count of vertices to draw
  13715. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13716. */
  13717. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13718. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13719. };
  13720. /**
  13721. * Draw a list of unindexed primitives
  13722. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13723. * @param verticesStart defines the index of first vertex to draw
  13724. * @param verticesCount defines the count of vertices to draw
  13725. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13726. */
  13727. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13728. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13729. };
  13730. /**
  13731. * Draw a list of indexed primitives
  13732. * @param fillMode defines the primitive to use
  13733. * @param indexStart defines the starting index
  13734. * @param indexCount defines the number of index to draw
  13735. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13736. */
  13737. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13738. // Apply states
  13739. this.applyStates();
  13740. this._drawCalls.addCount(1, false);
  13741. // Render
  13742. var drawMode = this._drawMode(fillMode);
  13743. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13744. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13745. if (instancesCount) {
  13746. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13747. }
  13748. else {
  13749. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13750. }
  13751. };
  13752. /**
  13753. * Draw a list of unindexed primitives
  13754. * @param fillMode defines the primitive to use
  13755. * @param verticesStart defines the index of first vertex to draw
  13756. * @param verticesCount defines the count of vertices to draw
  13757. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13758. */
  13759. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13760. // Apply states
  13761. this.applyStates();
  13762. this._drawCalls.addCount(1, false);
  13763. var drawMode = this._drawMode(fillMode);
  13764. if (instancesCount) {
  13765. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13766. }
  13767. else {
  13768. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13769. }
  13770. };
  13771. Engine.prototype._drawMode = function (fillMode) {
  13772. switch (fillMode) {
  13773. // Triangle views
  13774. case BABYLON.Material.TriangleFillMode:
  13775. return this._gl.TRIANGLES;
  13776. case BABYLON.Material.PointFillMode:
  13777. return this._gl.POINTS;
  13778. case BABYLON.Material.WireFrameFillMode:
  13779. return this._gl.LINES;
  13780. // Draw modes
  13781. case BABYLON.Material.PointListDrawMode:
  13782. return this._gl.POINTS;
  13783. case BABYLON.Material.LineListDrawMode:
  13784. return this._gl.LINES;
  13785. case BABYLON.Material.LineLoopDrawMode:
  13786. return this._gl.LINE_LOOP;
  13787. case BABYLON.Material.LineStripDrawMode:
  13788. return this._gl.LINE_STRIP;
  13789. case BABYLON.Material.TriangleStripDrawMode:
  13790. return this._gl.TRIANGLE_STRIP;
  13791. case BABYLON.Material.TriangleFanDrawMode:
  13792. return this._gl.TRIANGLE_FAN;
  13793. default:
  13794. return this._gl.TRIANGLES;
  13795. }
  13796. };
  13797. // Shaders
  13798. /** @hidden */
  13799. Engine.prototype._releaseEffect = function (effect) {
  13800. if (this._compiledEffects[effect._key]) {
  13801. delete this._compiledEffects[effect._key];
  13802. this._deleteProgram(effect.getProgram());
  13803. }
  13804. };
  13805. /** @hidden */
  13806. Engine.prototype._deleteProgram = function (program) {
  13807. if (program) {
  13808. program.__SPECTOR_rebuildProgram = null;
  13809. if (program.transformFeedback) {
  13810. this.deleteTransformFeedback(program.transformFeedback);
  13811. program.transformFeedback = null;
  13812. }
  13813. this._gl.deleteProgram(program);
  13814. }
  13815. };
  13816. /**
  13817. * Create a new effect (used to store vertex/fragment shaders)
  13818. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13819. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13820. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13821. * @param samplers defines an array of string used to represent textures
  13822. * @param defines defines the string containing the defines to use to compile the shaders
  13823. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13824. * @param onCompiled defines a function to call when the effect creation is successful
  13825. * @param onError defines a function to call when the effect creation has failed
  13826. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13827. * @returns the new Effect
  13828. */
  13829. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13830. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13831. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13832. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13833. if (this._compiledEffects[name]) {
  13834. var compiledEffect = this._compiledEffects[name];
  13835. if (onCompiled && compiledEffect.isReady()) {
  13836. onCompiled(compiledEffect);
  13837. }
  13838. return compiledEffect;
  13839. }
  13840. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13841. effect._key = name;
  13842. this._compiledEffects[name] = effect;
  13843. return effect;
  13844. };
  13845. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13846. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13847. };
  13848. ;
  13849. Engine.prototype._compileRawShader = function (source, type) {
  13850. var gl = this._gl;
  13851. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13852. gl.shaderSource(shader, source);
  13853. gl.compileShader(shader);
  13854. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13855. var log = gl.getShaderInfoLog(shader);
  13856. if (log) {
  13857. throw new Error(log);
  13858. }
  13859. }
  13860. if (!shader) {
  13861. throw new Error("Something went wrong while compile the shader.");
  13862. }
  13863. return shader;
  13864. };
  13865. ;
  13866. /**
  13867. * Directly creates a webGL program
  13868. * @param vertexCode defines the vertex shader code to use
  13869. * @param fragmentCode defines the fragment shader code to use
  13870. * @param context defines the webGL context to use (if not set, the current one will be used)
  13871. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13872. * @returns the new webGL program
  13873. */
  13874. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13875. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13876. context = context || this._gl;
  13877. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13878. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13879. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13880. };
  13881. /**
  13882. * Creates a webGL program
  13883. * @param vertexCode defines the vertex shader code to use
  13884. * @param fragmentCode defines the fragment shader code to use
  13885. * @param defines defines the string containing the defines to use to compile the shaders
  13886. * @param context defines the webGL context to use (if not set, the current one will be used)
  13887. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13888. * @returns the new webGL program
  13889. */
  13890. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13891. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13892. context = context || this._gl;
  13893. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13894. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13895. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13896. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13897. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13898. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13899. return program;
  13900. };
  13901. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13902. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13903. var shaderProgram = context.createProgram();
  13904. if (!shaderProgram) {
  13905. throw new Error("Unable to create program");
  13906. }
  13907. context.attachShader(shaderProgram, vertexShader);
  13908. context.attachShader(shaderProgram, fragmentShader);
  13909. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13910. var transformFeedback = this.createTransformFeedback();
  13911. this.bindTransformFeedback(transformFeedback);
  13912. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13913. shaderProgram.transformFeedback = transformFeedback;
  13914. }
  13915. context.linkProgram(shaderProgram);
  13916. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13917. this.bindTransformFeedback(null);
  13918. }
  13919. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13920. if (!linked) {
  13921. var error = context.getProgramInfoLog(shaderProgram);
  13922. if (error) {
  13923. throw new Error(error);
  13924. }
  13925. }
  13926. if (this.validateShaderPrograms) {
  13927. context.validateProgram(shaderProgram);
  13928. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13929. if (!validated) {
  13930. var error = context.getProgramInfoLog(shaderProgram);
  13931. if (error) {
  13932. throw new Error(error);
  13933. }
  13934. }
  13935. }
  13936. context.deleteShader(vertexShader);
  13937. context.deleteShader(fragmentShader);
  13938. return shaderProgram;
  13939. };
  13940. /**
  13941. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13942. * @param shaderProgram defines the webGL program to use
  13943. * @param uniformsNames defines the list of uniform names
  13944. * @returns an array of webGL uniform locations
  13945. */
  13946. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13947. var results = new Array();
  13948. for (var index = 0; index < uniformsNames.length; index++) {
  13949. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13950. }
  13951. return results;
  13952. };
  13953. /**
  13954. * Gets the lsit of active attributes for a given webGL program
  13955. * @param shaderProgram defines the webGL program to use
  13956. * @param attributesNames defines the list of attribute names to get
  13957. * @returns an array of indices indicating the offset of each attribute
  13958. */
  13959. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13960. var results = [];
  13961. for (var index = 0; index < attributesNames.length; index++) {
  13962. try {
  13963. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13964. }
  13965. catch (e) {
  13966. results.push(-1);
  13967. }
  13968. }
  13969. return results;
  13970. };
  13971. /**
  13972. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13973. * @param effect defines the effect to activate
  13974. */
  13975. Engine.prototype.enableEffect = function (effect) {
  13976. if (!effect || effect === this._currentEffect) {
  13977. return;
  13978. }
  13979. // Use program
  13980. this.bindSamplers(effect);
  13981. this._currentEffect = effect;
  13982. if (effect.onBind) {
  13983. effect.onBind(effect);
  13984. }
  13985. if (effect._onBindObservable) {
  13986. effect._onBindObservable.notifyObservers(effect);
  13987. }
  13988. };
  13989. /**
  13990. * Set the value of an uniform to an array of int32
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param array defines the array of int32 to store
  13993. */
  13994. Engine.prototype.setIntArray = function (uniform, array) {
  13995. if (!uniform)
  13996. return;
  13997. this._gl.uniform1iv(uniform, array);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to an array of int32 (stored as vec2)
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param array defines the array of int32 to store
  14003. */
  14004. Engine.prototype.setIntArray2 = function (uniform, array) {
  14005. if (!uniform || array.length % 2 !== 0)
  14006. return;
  14007. this._gl.uniform2iv(uniform, array);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to an array of int32 (stored as vec3)
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param array defines the array of int32 to store
  14013. */
  14014. Engine.prototype.setIntArray3 = function (uniform, array) {
  14015. if (!uniform || array.length % 3 !== 0)
  14016. return;
  14017. this._gl.uniform3iv(uniform, array);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to an array of int32 (stored as vec4)
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param array defines the array of int32 to store
  14023. */
  14024. Engine.prototype.setIntArray4 = function (uniform, array) {
  14025. if (!uniform || array.length % 4 !== 0)
  14026. return;
  14027. this._gl.uniform4iv(uniform, array);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to an array of float32
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param array defines the array of float32 to store
  14033. */
  14034. Engine.prototype.setFloatArray = function (uniform, array) {
  14035. if (!uniform)
  14036. return;
  14037. this._gl.uniform1fv(uniform, array);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of float32 (stored as vec2)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param array defines the array of float32 to store
  14043. */
  14044. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14045. if (!uniform || array.length % 2 !== 0)
  14046. return;
  14047. this._gl.uniform2fv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of float32 (stored as vec3)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of float32 to store
  14053. */
  14054. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14055. if (!uniform || array.length % 3 !== 0)
  14056. return;
  14057. this._gl.uniform3fv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of float32 (stored as vec4)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of float32 to store
  14063. */
  14064. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14065. if (!uniform || array.length % 4 !== 0)
  14066. return;
  14067. this._gl.uniform4fv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of number
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of number to store
  14073. */
  14074. Engine.prototype.setArray = function (uniform, array) {
  14075. if (!uniform)
  14076. return;
  14077. this._gl.uniform1fv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of number (stored as vec2)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of number to store
  14083. */
  14084. Engine.prototype.setArray2 = function (uniform, array) {
  14085. if (!uniform || array.length % 2 !== 0)
  14086. return;
  14087. this._gl.uniform2fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of number (stored as vec3)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of number to store
  14093. */
  14094. Engine.prototype.setArray3 = function (uniform, array) {
  14095. if (!uniform || array.length % 3 !== 0)
  14096. return;
  14097. this._gl.uniform3fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of number (stored as vec4)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of number to store
  14103. */
  14104. Engine.prototype.setArray4 = function (uniform, array) {
  14105. if (!uniform || array.length % 4 !== 0)
  14106. return;
  14107. this._gl.uniform4fv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of float32 (stored as matrices)
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param matrices defines the array of float32 to store
  14113. */
  14114. Engine.prototype.setMatrices = function (uniform, matrices) {
  14115. if (!uniform)
  14116. return;
  14117. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to a matrix
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param matrix defines the matrix to store
  14123. */
  14124. Engine.prototype.setMatrix = function (uniform, matrix) {
  14125. if (!uniform)
  14126. return;
  14127. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14128. };
  14129. /**
  14130. * Set the value of an uniform to a matrix (3x3)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14133. */
  14134. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a matrix (2x2)
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14143. */
  14144. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a number (int)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param value defines the int number to store
  14153. */
  14154. Engine.prototype.setInt = function (uniform, value) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniform1i(uniform, value);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to a number (float)
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param value defines the float number to store
  14163. */
  14164. Engine.prototype.setFloat = function (uniform, value) {
  14165. if (!uniform)
  14166. return;
  14167. this._gl.uniform1f(uniform, value);
  14168. };
  14169. /**
  14170. * Set the value of an uniform to a vec2
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param x defines the 1st component of the value
  14173. * @param y defines the 2nd component of the value
  14174. */
  14175. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14176. if (!uniform)
  14177. return;
  14178. this._gl.uniform2f(uniform, x, y);
  14179. };
  14180. /**
  14181. * Set the value of an uniform to a vec3
  14182. * @param uniform defines the webGL uniform location where to store the value
  14183. * @param x defines the 1st component of the value
  14184. * @param y defines the 2nd component of the value
  14185. * @param z defines the 3rd component of the value
  14186. */
  14187. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14188. if (!uniform)
  14189. return;
  14190. this._gl.uniform3f(uniform, x, y, z);
  14191. };
  14192. /**
  14193. * Set the value of an uniform to a boolean
  14194. * @param uniform defines the webGL uniform location where to store the value
  14195. * @param bool defines the boolean to store
  14196. */
  14197. Engine.prototype.setBool = function (uniform, bool) {
  14198. if (!uniform)
  14199. return;
  14200. this._gl.uniform1i(uniform, bool);
  14201. };
  14202. /**
  14203. * Set the value of an uniform to a vec4
  14204. * @param uniform defines the webGL uniform location where to store the value
  14205. * @param x defines the 1st component of the value
  14206. * @param y defines the 2nd component of the value
  14207. * @param z defines the 3rd component of the value
  14208. * @param w defines the 4th component of the value
  14209. */
  14210. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14211. if (!uniform)
  14212. return;
  14213. this._gl.uniform4f(uniform, x, y, z, w);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to a Color3
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param color3 defines the color to store
  14219. */
  14220. Engine.prototype.setColor3 = function (uniform, color3) {
  14221. if (!uniform)
  14222. return;
  14223. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14224. };
  14225. /**
  14226. * Set the value of an uniform to a Color3 and an alpha value
  14227. * @param uniform defines the webGL uniform location where to store the value
  14228. * @param color3 defines the color to store
  14229. * @param alpha defines the alpha component to store
  14230. */
  14231. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14235. };
  14236. /**
  14237. * Sets a Color4 on a uniform variable
  14238. * @param uniform defines the uniform location
  14239. * @param color4 defines the value to be set
  14240. */
  14241. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14242. if (!uniform)
  14243. return;
  14244. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14245. };
  14246. // States
  14247. /**
  14248. * Set various states to the webGL context
  14249. * @param culling defines backface culling state
  14250. * @param zOffset defines the value to apply to zOffset (0 by default)
  14251. * @param force defines if states must be applied even if cache is up to date
  14252. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14253. */
  14254. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14255. if (zOffset === void 0) { zOffset = 0; }
  14256. if (reverseSide === void 0) { reverseSide = false; }
  14257. // Culling
  14258. if (this._depthCullingState.cull !== culling || force) {
  14259. this._depthCullingState.cull = culling;
  14260. }
  14261. // Cull face
  14262. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14263. if (this._depthCullingState.cullFace !== cullFace || force) {
  14264. this._depthCullingState.cullFace = cullFace;
  14265. }
  14266. // Z offset
  14267. this.setZOffset(zOffset);
  14268. // Front face
  14269. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14270. if (this._depthCullingState.frontFace !== frontFace || force) {
  14271. this._depthCullingState.frontFace = frontFace;
  14272. }
  14273. };
  14274. /**
  14275. * Set the z offset to apply to current rendering
  14276. * @param value defines the offset to apply
  14277. */
  14278. Engine.prototype.setZOffset = function (value) {
  14279. this._depthCullingState.zOffset = value;
  14280. };
  14281. /**
  14282. * Gets the current value of the zOffset
  14283. * @returns the current zOffset state
  14284. */
  14285. Engine.prototype.getZOffset = function () {
  14286. return this._depthCullingState.zOffset;
  14287. };
  14288. /**
  14289. * Enable or disable depth buffering
  14290. * @param enable defines the state to set
  14291. */
  14292. Engine.prototype.setDepthBuffer = function (enable) {
  14293. this._depthCullingState.depthTest = enable;
  14294. };
  14295. /**
  14296. * Gets a boolean indicating if depth writing is enabled
  14297. * @returns the current depth writing state
  14298. */
  14299. Engine.prototype.getDepthWrite = function () {
  14300. return this._depthCullingState.depthMask;
  14301. };
  14302. /**
  14303. * Enable or disable depth writing
  14304. * @param enable defines the state to set
  14305. */
  14306. Engine.prototype.setDepthWrite = function (enable) {
  14307. this._depthCullingState.depthMask = enable;
  14308. };
  14309. /**
  14310. * Enable or disable color writing
  14311. * @param enable defines the state to set
  14312. */
  14313. Engine.prototype.setColorWrite = function (enable) {
  14314. this._gl.colorMask(enable, enable, enable, enable);
  14315. this._colorWrite = enable;
  14316. };
  14317. /**
  14318. * Gets a boolean indicating if color writing is enabled
  14319. * @returns the current color writing state
  14320. */
  14321. Engine.prototype.getColorWrite = function () {
  14322. return this._colorWrite;
  14323. };
  14324. /**
  14325. * Sets alpha constants used by some alpha blending modes
  14326. * @param r defines the red component
  14327. * @param g defines the green component
  14328. * @param b defines the blue component
  14329. * @param a defines the alpha component
  14330. */
  14331. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14332. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14333. };
  14334. /**
  14335. * Sets the current alpha mode
  14336. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14337. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14338. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14339. */
  14340. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14341. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14342. if (this._alphaMode === mode) {
  14343. return;
  14344. }
  14345. switch (mode) {
  14346. case Engine.ALPHA_DISABLE:
  14347. this._alphaState.alphaBlend = false;
  14348. break;
  14349. case Engine.ALPHA_PREMULTIPLIED:
  14350. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14351. this._alphaState.alphaBlend = true;
  14352. break;
  14353. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14354. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14355. this._alphaState.alphaBlend = true;
  14356. break;
  14357. case Engine.ALPHA_COMBINE:
  14358. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14359. this._alphaState.alphaBlend = true;
  14360. break;
  14361. case Engine.ALPHA_ONEONE:
  14362. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14363. this._alphaState.alphaBlend = true;
  14364. break;
  14365. case Engine.ALPHA_ADD:
  14366. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14367. this._alphaState.alphaBlend = true;
  14368. break;
  14369. case Engine.ALPHA_SUBTRACT:
  14370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14371. this._alphaState.alphaBlend = true;
  14372. break;
  14373. case Engine.ALPHA_MULTIPLY:
  14374. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14375. this._alphaState.alphaBlend = true;
  14376. break;
  14377. case Engine.ALPHA_MAXIMIZED:
  14378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14379. this._alphaState.alphaBlend = true;
  14380. break;
  14381. case Engine.ALPHA_INTERPOLATE:
  14382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14383. this._alphaState.alphaBlend = true;
  14384. break;
  14385. case Engine.ALPHA_SCREENMODE:
  14386. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14387. this._alphaState.alphaBlend = true;
  14388. break;
  14389. }
  14390. if (!noDepthWriteChange) {
  14391. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14392. }
  14393. this._alphaMode = mode;
  14394. };
  14395. /**
  14396. * Gets the current alpha mode
  14397. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14398. * @returns the current alpha mode
  14399. */
  14400. Engine.prototype.getAlphaMode = function () {
  14401. return this._alphaMode;
  14402. };
  14403. // Textures
  14404. /**
  14405. * Clears the list of texture accessible through engine.
  14406. * This can help preventing texture load conflict due to name collision.
  14407. */
  14408. Engine.prototype.clearInternalTexturesCache = function () {
  14409. this._internalTexturesCache = [];
  14410. };
  14411. /**
  14412. * Force the entire cache to be cleared
  14413. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14414. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14415. */
  14416. Engine.prototype.wipeCaches = function (bruteForce) {
  14417. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14418. return;
  14419. }
  14420. this._currentEffect = null;
  14421. this._viewportCached.x = 0;
  14422. this._viewportCached.y = 0;
  14423. this._viewportCached.z = 0;
  14424. this._viewportCached.w = 0;
  14425. if (bruteForce) {
  14426. this.resetTextureCache();
  14427. this._currentProgram = null;
  14428. this._stencilState.reset();
  14429. this._depthCullingState.reset();
  14430. this.setDepthFunctionToLessOrEqual();
  14431. this._alphaState.reset();
  14432. this._unpackFlipYCached = null;
  14433. }
  14434. this._resetVertexBufferBinding();
  14435. this._cachedIndexBuffer = null;
  14436. this._cachedEffectForVertexBuffers = null;
  14437. this._unbindVertexArrayObject();
  14438. this.bindIndexBuffer(null);
  14439. };
  14440. /**
  14441. * Set the compressed texture format to use, based on the formats you have, and the formats
  14442. * supported by the hardware / browser.
  14443. *
  14444. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14445. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14446. * to API arguments needed to compressed textures. This puts the burden on the container
  14447. * generator to house the arcane code for determining these for current & future formats.
  14448. *
  14449. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14450. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14451. *
  14452. * Note: The result of this call is not taken into account when a texture is base64.
  14453. *
  14454. * @param formatsAvailable defines the list of those format families you have created
  14455. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14456. *
  14457. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14458. * @returns The extension selected.
  14459. */
  14460. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14461. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14462. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14463. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14464. return this._textureFormatInUse = this._texturesSupported[i];
  14465. }
  14466. }
  14467. }
  14468. // actively set format to nothing, to allow this to be called more than once
  14469. // and possibly fail the 2nd time
  14470. this._textureFormatInUse = null;
  14471. return null;
  14472. };
  14473. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14474. var gl = this._gl;
  14475. var magFilter = gl.NEAREST;
  14476. var minFilter = gl.NEAREST;
  14477. switch (samplingMode) {
  14478. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14479. magFilter = gl.LINEAR;
  14480. if (generateMipMaps) {
  14481. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14482. }
  14483. else {
  14484. minFilter = gl.LINEAR;
  14485. }
  14486. break;
  14487. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14488. magFilter = gl.LINEAR;
  14489. if (generateMipMaps) {
  14490. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14491. }
  14492. else {
  14493. minFilter = gl.LINEAR;
  14494. }
  14495. break;
  14496. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14497. magFilter = gl.NEAREST;
  14498. if (generateMipMaps) {
  14499. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14500. }
  14501. else {
  14502. minFilter = gl.NEAREST;
  14503. }
  14504. break;
  14505. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14506. magFilter = gl.NEAREST;
  14507. if (generateMipMaps) {
  14508. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14509. }
  14510. else {
  14511. minFilter = gl.NEAREST;
  14512. }
  14513. break;
  14514. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14515. magFilter = gl.NEAREST;
  14516. if (generateMipMaps) {
  14517. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14518. }
  14519. else {
  14520. minFilter = gl.LINEAR;
  14521. }
  14522. break;
  14523. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14524. magFilter = gl.NEAREST;
  14525. if (generateMipMaps) {
  14526. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14527. }
  14528. else {
  14529. minFilter = gl.LINEAR;
  14530. }
  14531. break;
  14532. case Engine.TEXTURE_NEAREST_LINEAR:
  14533. magFilter = gl.NEAREST;
  14534. minFilter = gl.LINEAR;
  14535. break;
  14536. case Engine.TEXTURE_NEAREST_NEAREST:
  14537. magFilter = gl.NEAREST;
  14538. minFilter = gl.NEAREST;
  14539. break;
  14540. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14541. magFilter = gl.LINEAR;
  14542. if (generateMipMaps) {
  14543. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14544. }
  14545. else {
  14546. minFilter = gl.NEAREST;
  14547. }
  14548. break;
  14549. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14550. magFilter = gl.LINEAR;
  14551. if (generateMipMaps) {
  14552. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14553. }
  14554. else {
  14555. minFilter = gl.NEAREST;
  14556. }
  14557. break;
  14558. case Engine.TEXTURE_LINEAR_LINEAR:
  14559. magFilter = gl.LINEAR;
  14560. minFilter = gl.LINEAR;
  14561. break;
  14562. case Engine.TEXTURE_LINEAR_NEAREST:
  14563. magFilter = gl.LINEAR;
  14564. minFilter = gl.NEAREST;
  14565. break;
  14566. }
  14567. return {
  14568. min: minFilter,
  14569. mag: magFilter
  14570. };
  14571. };
  14572. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14573. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14574. var img;
  14575. var onload = function () {
  14576. loadedImages[index] = img;
  14577. loadedImages._internalCount++;
  14578. if (scene) {
  14579. scene._removePendingData(img);
  14580. }
  14581. if (loadedImages._internalCount === 6) {
  14582. onfinish(loadedImages);
  14583. }
  14584. };
  14585. var onerror = function (message, exception) {
  14586. if (scene) {
  14587. scene._removePendingData(img);
  14588. }
  14589. if (onErrorCallBack) {
  14590. onErrorCallBack(message, exception);
  14591. }
  14592. };
  14593. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14594. if (scene) {
  14595. scene._addPendingData(img);
  14596. }
  14597. };
  14598. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14599. if (onError === void 0) { onError = null; }
  14600. var loadedImages = [];
  14601. loadedImages._internalCount = 0;
  14602. for (var index = 0; index < 6; index++) {
  14603. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14604. }
  14605. };
  14606. ;
  14607. /** @hidden */
  14608. Engine.prototype._createTexture = function () {
  14609. var texture = this._gl.createTexture();
  14610. if (!texture) {
  14611. throw new Error("Unable to create texture");
  14612. }
  14613. return texture;
  14614. };
  14615. /**
  14616. * Usually called from BABYLON.Texture.ts.
  14617. * Passed information to create a WebGLTexture
  14618. * @param urlArg defines a value which contains one of the following:
  14619. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14620. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14621. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14622. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14623. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14624. * @param scene needed for loading to the correct scene
  14625. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14626. * @param onLoad optional callback to be called upon successful completion
  14627. * @param onError optional callback to be called upon failure
  14628. * @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
  14629. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14630. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14631. * @param forcedExtension defines the extension to use to pick the right loader
  14632. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14633. */
  14634. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14635. var _this = this;
  14636. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14637. if (onLoad === void 0) { onLoad = null; }
  14638. if (onError === void 0) { onError = null; }
  14639. if (buffer === void 0) { buffer = null; }
  14640. if (fallback === void 0) { fallback = null; }
  14641. if (format === void 0) { format = null; }
  14642. if (forcedExtension === void 0) { forcedExtension = null; }
  14643. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14644. var fromData = url.substr(0, 5) === "data:";
  14645. var fromBlob = url.substr(0, 5) === "blob:";
  14646. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14647. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14648. // establish the file extension, if possible
  14649. var lastDot = url.lastIndexOf('.');
  14650. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14651. var loader = null;
  14652. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14653. var availableLoader = _a[_i];
  14654. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14655. loader = availableLoader;
  14656. break;
  14657. }
  14658. }
  14659. if (loader) {
  14660. url = loader.transformUrl(url, this._textureFormatInUse);
  14661. }
  14662. if (scene) {
  14663. scene._addPendingData(texture);
  14664. }
  14665. texture.url = url;
  14666. texture.generateMipMaps = !noMipmap;
  14667. texture.samplingMode = samplingMode;
  14668. texture.invertY = invertY;
  14669. if (!this._doNotHandleContextLost) {
  14670. // Keep a link to the buffer only if we plan to handle context lost
  14671. texture._buffer = buffer;
  14672. }
  14673. var onLoadObserver = null;
  14674. if (onLoad && !fallback) {
  14675. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14676. }
  14677. if (!fallback)
  14678. this._internalTexturesCache.push(texture);
  14679. var onInternalError = function (message, exception) {
  14680. if (scene) {
  14681. scene._removePendingData(texture);
  14682. }
  14683. var customFallback = false;
  14684. if (loader) {
  14685. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14686. if (fallbackUrl) {
  14687. // Add Back
  14688. customFallback = true;
  14689. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14690. }
  14691. }
  14692. if (!customFallback) {
  14693. if (onLoadObserver) {
  14694. texture.onLoadedObservable.remove(onLoadObserver);
  14695. }
  14696. if (BABYLON.Tools.UseFallbackTexture) {
  14697. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14698. }
  14699. }
  14700. if (onError) {
  14701. onError(message || "Unknown error", exception);
  14702. }
  14703. };
  14704. // processing for non-image formats
  14705. if (loader) {
  14706. var callback = function (data) {
  14707. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14708. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14709. done();
  14710. return false;
  14711. }, samplingMode);
  14712. });
  14713. };
  14714. if (!buffer) {
  14715. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14716. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14717. });
  14718. }
  14719. else {
  14720. callback(buffer);
  14721. }
  14722. }
  14723. else {
  14724. var onload = function (img) {
  14725. if (fromBlob && !_this._doNotHandleContextLost) {
  14726. // We need to store the image if we need to rebuild the texture
  14727. // in case of a webgl context lost
  14728. texture._buffer = img;
  14729. }
  14730. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14731. var gl = _this._gl;
  14732. var isPot = (img.width === potWidth && img.height === potHeight);
  14733. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14734. if (isPot) {
  14735. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14736. return false;
  14737. }
  14738. var maxTextureSize = _this._caps.maxTextureSize;
  14739. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14740. _this._prepareWorkingCanvas();
  14741. if (!_this._workingCanvas || !_this._workingContext) {
  14742. return false;
  14743. }
  14744. _this._workingCanvas.width = potWidth;
  14745. _this._workingCanvas.height = potHeight;
  14746. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14747. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14748. texture.width = potWidth;
  14749. texture.height = potHeight;
  14750. return false;
  14751. }
  14752. else {
  14753. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14754. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14755. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14756. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14759. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14760. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14761. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14762. _this._releaseTexture(source_1);
  14763. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14764. continuationCallback();
  14765. });
  14766. }
  14767. return true;
  14768. }, samplingMode);
  14769. };
  14770. if (!fromData || isBase64) {
  14771. if (buffer instanceof HTMLImageElement) {
  14772. onload(buffer);
  14773. }
  14774. else {
  14775. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14776. }
  14777. }
  14778. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14779. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14780. }
  14781. else {
  14782. onload(buffer);
  14783. }
  14784. }
  14785. return texture;
  14786. };
  14787. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14788. var _this = this;
  14789. var rtt = this.createRenderTargetTexture({
  14790. width: destination.width,
  14791. height: destination.height,
  14792. }, {
  14793. generateMipMaps: false,
  14794. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14795. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14796. generateDepthBuffer: false,
  14797. generateStencilBuffer: false
  14798. });
  14799. if (!this._rescalePostProcess) {
  14800. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14801. }
  14802. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14803. _this._rescalePostProcess.onApply = function (effect) {
  14804. effect._bindTexture("textureSampler", source);
  14805. };
  14806. var hostingScene = scene;
  14807. if (!hostingScene) {
  14808. hostingScene = _this.scenes[_this.scenes.length - 1];
  14809. }
  14810. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14811. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14812. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14813. _this.unBindFramebuffer(rtt);
  14814. _this._releaseTexture(rtt);
  14815. if (onComplete) {
  14816. onComplete();
  14817. }
  14818. });
  14819. };
  14820. /**
  14821. * Update a raw texture
  14822. * @param texture defines the texture to update
  14823. * @param data defines the data to store in the texture
  14824. * @param format defines the format of the data
  14825. * @param invertY defines if data must be stored with Y axis inverted
  14826. * @param compression defines the compression used (null by default)
  14827. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14828. */
  14829. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14830. if (compression === void 0) { compression = null; }
  14831. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14832. if (!texture) {
  14833. return;
  14834. }
  14835. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14836. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14837. // babylon's internalFormat but gl's texImage2D format
  14838. var internalFormat = this._getInternalFormat(format);
  14839. var textureType = this._getWebGLTextureType(type);
  14840. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14841. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14842. if (!this._doNotHandleContextLost) {
  14843. texture._bufferView = data;
  14844. texture.format = format;
  14845. texture.type = type;
  14846. texture.invertY = invertY;
  14847. texture._compression = compression;
  14848. }
  14849. if (texture.width % 4 !== 0) {
  14850. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14851. }
  14852. if (compression && data) {
  14853. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14854. }
  14855. else {
  14856. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14857. }
  14858. if (texture.generateMipMaps) {
  14859. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14860. }
  14861. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14862. // this.resetTextureCache();
  14863. texture.isReady = true;
  14864. };
  14865. /**
  14866. * Creates a raw texture
  14867. * @param data defines the data to store in the texture
  14868. * @param width defines the width of the texture
  14869. * @param height defines the height of the texture
  14870. * @param format defines the format of the data
  14871. * @param generateMipMaps defines if the engine should generate the mip levels
  14872. * @param invertY defines if data must be stored with Y axis inverted
  14873. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14874. * @param compression defines the compression used (null by default)
  14875. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14876. * @returns the raw texture inside an InternalTexture
  14877. */
  14878. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14879. if (compression === void 0) { compression = null; }
  14880. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14881. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14882. texture.baseWidth = width;
  14883. texture.baseHeight = height;
  14884. texture.width = width;
  14885. texture.height = height;
  14886. texture.format = format;
  14887. texture.generateMipMaps = generateMipMaps;
  14888. texture.samplingMode = samplingMode;
  14889. texture.invertY = invertY;
  14890. texture._compression = compression;
  14891. texture.type = type;
  14892. if (!this._doNotHandleContextLost) {
  14893. texture._bufferView = data;
  14894. }
  14895. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14896. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14897. // Filters
  14898. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14900. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14901. if (generateMipMaps) {
  14902. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14903. }
  14904. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14905. this._internalTexturesCache.push(texture);
  14906. return texture;
  14907. };
  14908. /** @hidden */
  14909. Engine.prototype._unpackFlipY = function (value) {
  14910. if (this._unpackFlipYCached !== value) {
  14911. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14912. if (this.enableUnpackFlipYCached) {
  14913. this._unpackFlipYCached = value;
  14914. }
  14915. }
  14916. };
  14917. /** @hidden */
  14918. Engine.prototype._getUnpackAlignement = function () {
  14919. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14920. };
  14921. /**
  14922. * Creates a dynamic texture
  14923. * @param width defines the width of the texture
  14924. * @param height defines the height of the texture
  14925. * @param generateMipMaps defines if the engine should generate the mip levels
  14926. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14927. * @returns the dynamic texture inside an InternalTexture
  14928. */
  14929. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14930. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14931. texture.baseWidth = width;
  14932. texture.baseHeight = height;
  14933. if (generateMipMaps) {
  14934. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14935. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14936. }
  14937. // this.resetTextureCache();
  14938. texture.width = width;
  14939. texture.height = height;
  14940. texture.isReady = false;
  14941. texture.generateMipMaps = generateMipMaps;
  14942. texture.samplingMode = samplingMode;
  14943. this.updateTextureSamplingMode(samplingMode, texture);
  14944. this._internalTexturesCache.push(texture);
  14945. return texture;
  14946. };
  14947. /**
  14948. * Update the sampling mode of a given texture
  14949. * @param samplingMode defines the required sampling mode
  14950. * @param texture defines the texture to update
  14951. */
  14952. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14953. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14954. if (texture.isCube) {
  14955. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14956. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14957. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14958. }
  14959. else if (texture.is3D) {
  14960. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14961. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14962. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14963. }
  14964. else {
  14965. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14966. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14967. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14968. }
  14969. texture.samplingMode = samplingMode;
  14970. };
  14971. /**
  14972. * Update the content of a dynamic texture
  14973. * @param texture defines the texture to update
  14974. * @param canvas defines the canvas containing the source
  14975. * @param invertY defines if data must be stored with Y axis inverted
  14976. * @param premulAlpha defines if alpha is stored as premultiplied
  14977. * @param format defines the format of the data
  14978. */
  14979. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14980. if (premulAlpha === void 0) { premulAlpha = false; }
  14981. if (!texture) {
  14982. return;
  14983. }
  14984. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14985. this._unpackFlipY(invertY);
  14986. if (premulAlpha) {
  14987. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14988. }
  14989. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14990. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14991. if (texture.generateMipMaps) {
  14992. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14993. }
  14994. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14995. if (premulAlpha) {
  14996. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14997. }
  14998. texture.isReady = true;
  14999. };
  15000. /**
  15001. * Update a video texture
  15002. * @param texture defines the texture to update
  15003. * @param video defines the video element to use
  15004. * @param invertY defines if data must be stored with Y axis inverted
  15005. */
  15006. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15007. if (!texture || texture._isDisabled) {
  15008. return;
  15009. }
  15010. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15011. this._unpackFlipY(!invertY); // Video are upside down by default
  15012. try {
  15013. // Testing video texture support
  15014. if (this._videoTextureSupported === undefined) {
  15015. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15016. if (this._gl.getError() !== 0) {
  15017. this._videoTextureSupported = false;
  15018. }
  15019. else {
  15020. this._videoTextureSupported = true;
  15021. }
  15022. }
  15023. // Copy video through the current working canvas if video texture is not supported
  15024. if (!this._videoTextureSupported) {
  15025. if (!texture._workingCanvas) {
  15026. texture._workingCanvas = document.createElement("canvas");
  15027. var context = texture._workingCanvas.getContext("2d");
  15028. if (!context) {
  15029. throw new Error("Unable to get 2d context");
  15030. }
  15031. texture._workingContext = context;
  15032. texture._workingCanvas.width = texture.width;
  15033. texture._workingCanvas.height = texture.height;
  15034. }
  15035. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15036. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15037. }
  15038. else {
  15039. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15040. }
  15041. if (texture.generateMipMaps) {
  15042. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15043. }
  15044. if (!wasPreviouslyBound) {
  15045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15046. }
  15047. // this.resetTextureCache();
  15048. texture.isReady = true;
  15049. }
  15050. catch (ex) {
  15051. // Something unexpected
  15052. // Let's disable the texture
  15053. texture._isDisabled = true;
  15054. }
  15055. };
  15056. /**
  15057. * Updates a depth texture Comparison Mode and Function.
  15058. * If the comparison Function is equal to 0, the mode will be set to none.
  15059. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15060. * @param texture The texture to set the comparison function for
  15061. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15062. */
  15063. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15064. if (this.webGLVersion === 1) {
  15065. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15066. return;
  15067. }
  15068. var gl = this._gl;
  15069. if (texture.isCube) {
  15070. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15071. if (comparisonFunction === 0) {
  15072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15074. }
  15075. else {
  15076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15078. }
  15079. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15080. }
  15081. else {
  15082. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15083. if (comparisonFunction === 0) {
  15084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15086. }
  15087. else {
  15088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15090. }
  15091. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15092. }
  15093. texture._comparisonFunction = comparisonFunction;
  15094. };
  15095. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15096. var width = size.width || size;
  15097. var height = size.height || size;
  15098. internalTexture.baseWidth = width;
  15099. internalTexture.baseHeight = height;
  15100. internalTexture.width = width;
  15101. internalTexture.height = height;
  15102. internalTexture.isReady = true;
  15103. internalTexture.samples = 1;
  15104. internalTexture.generateMipMaps = false;
  15105. internalTexture._generateDepthBuffer = true;
  15106. internalTexture._generateStencilBuffer = generateStencil;
  15107. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15108. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15109. internalTexture._comparisonFunction = comparisonFunction;
  15110. var gl = this._gl;
  15111. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15112. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15113. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15114. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15115. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15116. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15117. if (comparisonFunction === 0) {
  15118. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15119. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15120. }
  15121. else {
  15122. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15123. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15124. }
  15125. };
  15126. /**
  15127. * Creates a depth stencil texture.
  15128. * This is only available in WebGL 2 or with the depth texture extension available.
  15129. * @param size The size of face edge in the texture.
  15130. * @param options The options defining the texture.
  15131. * @returns The texture
  15132. */
  15133. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15134. if (options.isCube) {
  15135. var width = size.width || size;
  15136. return this._createDepthStencilCubeTexture(width, options);
  15137. }
  15138. else {
  15139. return this._createDepthStencilTexture(size, options);
  15140. }
  15141. };
  15142. /**
  15143. * Creates a depth stencil texture.
  15144. * This is only available in WebGL 2 or with the depth texture extension available.
  15145. * @param size The size of face edge in the texture.
  15146. * @param options The options defining the texture.
  15147. * @returns The texture
  15148. */
  15149. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15150. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15151. if (!this._caps.depthTextureExtension) {
  15152. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15153. return internalTexture;
  15154. }
  15155. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15156. var gl = this._gl;
  15157. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15158. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15159. if (this.webGLVersion > 1) {
  15160. if (internalOptions.generateStencil) {
  15161. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15162. }
  15163. else {
  15164. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15165. }
  15166. }
  15167. else {
  15168. if (internalOptions.generateStencil) {
  15169. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15170. }
  15171. else {
  15172. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15173. }
  15174. }
  15175. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15176. return internalTexture;
  15177. };
  15178. /**
  15179. * Creates a depth stencil cube texture.
  15180. * This is only available in WebGL 2.
  15181. * @param size The size of face edge in the cube texture.
  15182. * @param options The options defining the cube texture.
  15183. * @returns The cube texture
  15184. */
  15185. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15186. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15187. internalTexture.isCube = true;
  15188. if (this.webGLVersion === 1) {
  15189. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15190. return internalTexture;
  15191. }
  15192. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15193. var gl = this._gl;
  15194. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15195. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15196. // Create the depth/stencil buffer
  15197. for (var face = 0; face < 6; face++) {
  15198. if (internalOptions.generateStencil) {
  15199. 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);
  15200. }
  15201. else {
  15202. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15203. }
  15204. }
  15205. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15206. return internalTexture;
  15207. };
  15208. /**
  15209. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15210. * @param renderTarget The render target to set the frame buffer for
  15211. */
  15212. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15213. // Create the framebuffer
  15214. var internalTexture = renderTarget.getInternalTexture();
  15215. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15216. return;
  15217. }
  15218. var gl = this._gl;
  15219. var depthStencilTexture = renderTarget.depthStencilTexture;
  15220. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15221. if (depthStencilTexture.isCube) {
  15222. if (depthStencilTexture._generateStencilBuffer) {
  15223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15224. }
  15225. else {
  15226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15227. }
  15228. }
  15229. else {
  15230. if (depthStencilTexture._generateStencilBuffer) {
  15231. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15232. }
  15233. else {
  15234. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15235. }
  15236. }
  15237. this.bindUnboundFramebuffer(null);
  15238. };
  15239. /**
  15240. * Creates a new render target texture
  15241. * @param size defines the size of the texture
  15242. * @param options defines the options used to create the texture
  15243. * @returns a new render target texture stored in an InternalTexture
  15244. */
  15245. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15246. var fullOptions = new RenderTargetCreationOptions();
  15247. if (options !== undefined && typeof options === "object") {
  15248. fullOptions.generateMipMaps = options.generateMipMaps;
  15249. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15250. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15251. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15252. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15253. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15254. }
  15255. else {
  15256. fullOptions.generateMipMaps = options;
  15257. fullOptions.generateDepthBuffer = true;
  15258. fullOptions.generateStencilBuffer = false;
  15259. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15260. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15261. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15262. }
  15263. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15264. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15265. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15266. }
  15267. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15268. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15269. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15270. }
  15271. var gl = this._gl;
  15272. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15273. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15274. var width = size.width || size;
  15275. var height = size.height || size;
  15276. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15277. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15278. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15279. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15280. }
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15285. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15286. // Create the framebuffer
  15287. var currentFrameBuffer = this._currentFramebuffer;
  15288. var framebuffer = gl.createFramebuffer();
  15289. this.bindUnboundFramebuffer(framebuffer);
  15290. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15291. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15292. if (fullOptions.generateMipMaps) {
  15293. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15294. }
  15295. // Unbind
  15296. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15297. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15298. this.bindUnboundFramebuffer(currentFrameBuffer);
  15299. texture._framebuffer = framebuffer;
  15300. texture.baseWidth = width;
  15301. texture.baseHeight = height;
  15302. texture.width = width;
  15303. texture.height = height;
  15304. texture.isReady = true;
  15305. texture.samples = 1;
  15306. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15307. texture.samplingMode = fullOptions.samplingMode;
  15308. texture.type = fullOptions.type;
  15309. texture.format = fullOptions.format;
  15310. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15311. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15312. // this.resetTextureCache();
  15313. this._internalTexturesCache.push(texture);
  15314. return texture;
  15315. };
  15316. /**
  15317. * Create a multi render target texture
  15318. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15319. * @param size defines the size of the texture
  15320. * @param options defines the creation options
  15321. * @returns the cube texture as an InternalTexture
  15322. */
  15323. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15324. var generateMipMaps = false;
  15325. var generateDepthBuffer = true;
  15326. var generateStencilBuffer = false;
  15327. var generateDepthTexture = false;
  15328. var textureCount = 1;
  15329. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15330. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15331. var types = new Array();
  15332. var samplingModes = new Array();
  15333. if (options !== undefined) {
  15334. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15335. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15336. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15337. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15338. textureCount = options.textureCount || 1;
  15339. if (options.types) {
  15340. types = options.types;
  15341. }
  15342. if (options.samplingModes) {
  15343. samplingModes = options.samplingModes;
  15344. }
  15345. }
  15346. var gl = this._gl;
  15347. // Create the framebuffer
  15348. var framebuffer = gl.createFramebuffer();
  15349. this.bindUnboundFramebuffer(framebuffer);
  15350. var width = size.width || size;
  15351. var height = size.height || size;
  15352. var textures = [];
  15353. var attachments = [];
  15354. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15355. for (var i = 0; i < textureCount; i++) {
  15356. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15357. var type = types[i] || defaultType;
  15358. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15359. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15360. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15361. }
  15362. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15363. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15364. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15365. }
  15366. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15367. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15368. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15369. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15370. }
  15371. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15372. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15373. textures.push(texture);
  15374. attachments.push(attachment);
  15375. gl.activeTexture(gl["TEXTURE" + i]);
  15376. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15381. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15382. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15383. if (generateMipMaps) {
  15384. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15385. }
  15386. // Unbind
  15387. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15388. texture._framebuffer = framebuffer;
  15389. texture._depthStencilBuffer = depthStencilBuffer;
  15390. texture.baseWidth = width;
  15391. texture.baseHeight = height;
  15392. texture.width = width;
  15393. texture.height = height;
  15394. texture.isReady = true;
  15395. texture.samples = 1;
  15396. texture.generateMipMaps = generateMipMaps;
  15397. texture.samplingMode = samplingMode;
  15398. texture.type = type;
  15399. texture._generateDepthBuffer = generateDepthBuffer;
  15400. texture._generateStencilBuffer = generateStencilBuffer;
  15401. texture._attachments = attachments;
  15402. this._internalTexturesCache.push(texture);
  15403. }
  15404. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15405. // Depth texture
  15406. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15407. gl.activeTexture(gl.TEXTURE0);
  15408. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15413. 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);
  15414. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15415. depthTexture._framebuffer = framebuffer;
  15416. depthTexture.baseWidth = width;
  15417. depthTexture.baseHeight = height;
  15418. depthTexture.width = width;
  15419. depthTexture.height = height;
  15420. depthTexture.isReady = true;
  15421. depthTexture.samples = 1;
  15422. depthTexture.generateMipMaps = generateMipMaps;
  15423. depthTexture.samplingMode = gl.NEAREST;
  15424. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15425. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15426. textures.push(depthTexture);
  15427. this._internalTexturesCache.push(depthTexture);
  15428. }
  15429. gl.drawBuffers(attachments);
  15430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15431. this.bindUnboundFramebuffer(null);
  15432. this.resetTextureCache();
  15433. return textures;
  15434. };
  15435. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15436. if (samples === void 0) { samples = 1; }
  15437. var depthStencilBuffer = null;
  15438. var gl = this._gl;
  15439. // Create the depth/stencil buffer
  15440. if (generateStencilBuffer) {
  15441. depthStencilBuffer = gl.createRenderbuffer();
  15442. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15443. if (samples > 1) {
  15444. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15445. }
  15446. else {
  15447. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15448. }
  15449. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15450. }
  15451. else if (generateDepthBuffer) {
  15452. depthStencilBuffer = gl.createRenderbuffer();
  15453. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15454. if (samples > 1) {
  15455. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15456. }
  15457. else {
  15458. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15459. }
  15460. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15461. }
  15462. return depthStencilBuffer;
  15463. };
  15464. /**
  15465. * Updates the sample count of a render target texture
  15466. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15467. * @param texture defines the texture to update
  15468. * @param samples defines the sample count to set
  15469. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15470. */
  15471. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15472. if (this.webGLVersion < 2 || !texture) {
  15473. return 1;
  15474. }
  15475. if (texture.samples === samples) {
  15476. return samples;
  15477. }
  15478. var gl = this._gl;
  15479. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15480. // Dispose previous render buffers
  15481. if (texture._depthStencilBuffer) {
  15482. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15483. texture._depthStencilBuffer = null;
  15484. }
  15485. if (texture._MSAAFramebuffer) {
  15486. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15487. texture._MSAAFramebuffer = null;
  15488. }
  15489. if (texture._MSAARenderBuffer) {
  15490. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15491. texture._MSAARenderBuffer = null;
  15492. }
  15493. if (samples > 1) {
  15494. var framebuffer = gl.createFramebuffer();
  15495. if (!framebuffer) {
  15496. throw new Error("Unable to create multi sampled framebuffer");
  15497. }
  15498. texture._MSAAFramebuffer = framebuffer;
  15499. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15500. var colorRenderbuffer = gl.createRenderbuffer();
  15501. if (!colorRenderbuffer) {
  15502. throw new Error("Unable to create multi sampled framebuffer");
  15503. }
  15504. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15505. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15506. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15507. texture._MSAARenderBuffer = colorRenderbuffer;
  15508. }
  15509. else {
  15510. this.bindUnboundFramebuffer(texture._framebuffer);
  15511. }
  15512. texture.samples = samples;
  15513. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15514. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15515. this.bindUnboundFramebuffer(null);
  15516. return samples;
  15517. };
  15518. /**
  15519. * Update the sample count for a given multiple render target texture
  15520. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15521. * @param textures defines the textures to update
  15522. * @param samples defines the sample count to set
  15523. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15524. */
  15525. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15526. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15527. return 1;
  15528. }
  15529. if (textures[0].samples === samples) {
  15530. return samples;
  15531. }
  15532. var gl = this._gl;
  15533. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15534. // Dispose previous render buffers
  15535. if (textures[0]._depthStencilBuffer) {
  15536. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15537. textures[0]._depthStencilBuffer = null;
  15538. }
  15539. if (textures[0]._MSAAFramebuffer) {
  15540. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15541. textures[0]._MSAAFramebuffer = null;
  15542. }
  15543. for (var i = 0; i < textures.length; i++) {
  15544. if (textures[i]._MSAARenderBuffer) {
  15545. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15546. textures[i]._MSAARenderBuffer = null;
  15547. }
  15548. }
  15549. if (samples > 1) {
  15550. var framebuffer = gl.createFramebuffer();
  15551. if (!framebuffer) {
  15552. throw new Error("Unable to create multi sampled framebuffer");
  15553. }
  15554. this.bindUnboundFramebuffer(framebuffer);
  15555. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15556. var attachments = [];
  15557. for (var i = 0; i < textures.length; i++) {
  15558. var texture = textures[i];
  15559. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15560. var colorRenderbuffer = gl.createRenderbuffer();
  15561. if (!colorRenderbuffer) {
  15562. throw new Error("Unable to create multi sampled framebuffer");
  15563. }
  15564. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15565. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15566. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15567. texture._MSAAFramebuffer = framebuffer;
  15568. texture._MSAARenderBuffer = colorRenderbuffer;
  15569. texture.samples = samples;
  15570. texture._depthStencilBuffer = depthStencilBuffer;
  15571. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15572. attachments.push(attachment);
  15573. }
  15574. gl.drawBuffers(attachments);
  15575. }
  15576. else {
  15577. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15578. }
  15579. this.bindUnboundFramebuffer(null);
  15580. return samples;
  15581. };
  15582. /** @hidden */
  15583. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15584. if (faceIndex === void 0) { faceIndex = 0; }
  15585. if (lod === void 0) { lod = 0; }
  15586. var gl = this._gl;
  15587. var target = gl.TEXTURE_2D;
  15588. if (texture.isCube) {
  15589. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15590. }
  15591. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15592. };
  15593. /** @hidden */
  15594. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15595. if (faceIndex === void 0) { faceIndex = 0; }
  15596. if (lod === void 0) { lod = 0; }
  15597. var gl = this._gl;
  15598. var textureType = this._getWebGLTextureType(texture.type);
  15599. var format = this._getInternalFormat(texture.format);
  15600. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15601. this._unpackFlipY(texture.invertY);
  15602. var target = gl.TEXTURE_2D;
  15603. if (texture.isCube) {
  15604. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15605. }
  15606. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15607. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15608. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15609. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15610. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15611. };
  15612. /** @hidden */
  15613. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15614. if (faceIndex === void 0) { faceIndex = 0; }
  15615. if (lod === void 0) { lod = 0; }
  15616. var gl = this._gl;
  15617. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15618. this._bindTextureDirectly(bindTarget, texture, true);
  15619. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15620. this._bindTextureDirectly(bindTarget, null, true);
  15621. };
  15622. /** @hidden */
  15623. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15624. if (faceIndex === void 0) { faceIndex = 0; }
  15625. if (lod === void 0) { lod = 0; }
  15626. var gl = this._gl;
  15627. var textureType = this._getWebGLTextureType(texture.type);
  15628. var format = this._getInternalFormat(texture.format);
  15629. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15630. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15631. this._bindTextureDirectly(bindTarget, texture, true);
  15632. this._unpackFlipY(texture.invertY);
  15633. var target = gl.TEXTURE_2D;
  15634. if (texture.isCube) {
  15635. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15636. }
  15637. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15638. this._bindTextureDirectly(bindTarget, null, true);
  15639. };
  15640. /**
  15641. * Creates a new render target cube texture
  15642. * @param size defines the size of the texture
  15643. * @param options defines the options used to create the texture
  15644. * @returns a new render target cube texture stored in an InternalTexture
  15645. */
  15646. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15647. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15648. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15649. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15650. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15651. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15652. }
  15653. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15654. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15655. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15656. }
  15657. var gl = this._gl;
  15658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15659. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15660. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15661. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15662. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15663. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15664. }
  15665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15669. for (var face = 0; face < 6; face++) {
  15670. 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);
  15671. }
  15672. // Create the framebuffer
  15673. var framebuffer = gl.createFramebuffer();
  15674. this.bindUnboundFramebuffer(framebuffer);
  15675. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15676. // MipMaps
  15677. if (fullOptions.generateMipMaps) {
  15678. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15679. }
  15680. // Unbind
  15681. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15682. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15683. this.bindUnboundFramebuffer(null);
  15684. texture._framebuffer = framebuffer;
  15685. texture.width = size;
  15686. texture.height = size;
  15687. texture.isReady = true;
  15688. texture.isCube = true;
  15689. texture.samples = 1;
  15690. texture.generateMipMaps = fullOptions.generateMipMaps;
  15691. texture.samplingMode = fullOptions.samplingMode;
  15692. texture.type = fullOptions.type;
  15693. texture.format = fullOptions.format;
  15694. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15695. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15696. this._internalTexturesCache.push(texture);
  15697. return texture;
  15698. };
  15699. /**
  15700. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15701. * @param rootUrl defines the url where the file to load is located
  15702. * @param scene defines the current scene
  15703. * @param lodScale defines scale to apply to the mip map selection
  15704. * @param lodOffset defines offset to apply to the mip map selection
  15705. * @param onLoad defines an optional callback raised when the texture is loaded
  15706. * @param onError defines an optional callback raised if there is an issue to load the texture
  15707. * @param format defines the format of the data
  15708. * @param forcedExtension defines the extension to use to pick the right loader
  15709. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15710. * @returns the cube texture as an InternalTexture
  15711. */
  15712. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15713. var _this = this;
  15714. if (onLoad === void 0) { onLoad = null; }
  15715. if (onError === void 0) { onError = null; }
  15716. if (forcedExtension === void 0) { forcedExtension = null; }
  15717. if (createPolynomials === void 0) { createPolynomials = true; }
  15718. var callback = function (loadData) {
  15719. if (!loadData) {
  15720. if (onLoad) {
  15721. onLoad(null);
  15722. }
  15723. return;
  15724. }
  15725. var texture = loadData.texture;
  15726. if (!createPolynomials) {
  15727. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15728. }
  15729. else if (loadData.info.sphericalPolynomial) {
  15730. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15731. }
  15732. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15733. if (_this._caps.textureLOD) {
  15734. // Do not add extra process if texture lod is supported.
  15735. if (onLoad) {
  15736. onLoad(texture);
  15737. }
  15738. return;
  15739. }
  15740. var mipSlices = 3;
  15741. var gl = _this._gl;
  15742. var width = loadData.width;
  15743. if (!width) {
  15744. return;
  15745. }
  15746. var textures = [];
  15747. for (var i = 0; i < mipSlices; i++) {
  15748. //compute LOD from even spacing in smoothness (matching shader calculation)
  15749. var smoothness = i / (mipSlices - 1);
  15750. var roughness = 1 - smoothness;
  15751. var minLODIndex = lodOffset; // roughness = 0
  15752. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15753. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15754. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15755. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15756. glTextureFromLod.type = texture.type;
  15757. glTextureFromLod.format = texture.format;
  15758. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15759. glTextureFromLod.height = glTextureFromLod.width;
  15760. glTextureFromLod.isCube = true;
  15761. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15766. if (loadData.isDDS) {
  15767. var info = loadData.info;
  15768. var data = loadData.data;
  15769. _this._unpackFlipY(info.isCompressed);
  15770. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15771. }
  15772. else {
  15773. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15774. }
  15775. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15776. // Wrap in a base texture for easy binding.
  15777. var lodTexture = new BABYLON.BaseTexture(scene);
  15778. lodTexture.isCube = true;
  15779. lodTexture._texture = glTextureFromLod;
  15780. glTextureFromLod.isReady = true;
  15781. textures.push(lodTexture);
  15782. }
  15783. texture._lodTextureHigh = textures[2];
  15784. texture._lodTextureMid = textures[1];
  15785. texture._lodTextureLow = textures[0];
  15786. if (onLoad) {
  15787. onLoad(texture);
  15788. }
  15789. };
  15790. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15791. };
  15792. /**
  15793. * Creates a cube texture
  15794. * @param rootUrl defines the url where the files to load is located
  15795. * @param scene defines the current scene
  15796. * @param files defines the list of files to load (1 per face)
  15797. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15798. * @param onLoad defines an optional callback raised when the texture is loaded
  15799. * @param onError defines an optional callback raised if there is an issue to load the texture
  15800. * @param format defines the format of the data
  15801. * @param forcedExtension defines the extension to use to pick the right loader
  15802. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15803. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15804. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15805. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15806. * @returns the cube texture as an InternalTexture
  15807. */
  15808. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15809. var _this = this;
  15810. if (onLoad === void 0) { onLoad = null; }
  15811. if (onError === void 0) { onError = null; }
  15812. if (forcedExtension === void 0) { forcedExtension = null; }
  15813. if (createPolynomials === void 0) { createPolynomials = false; }
  15814. if (lodScale === void 0) { lodScale = 0; }
  15815. if (lodOffset === void 0) { lodOffset = 0; }
  15816. if (fallback === void 0) { fallback = null; }
  15817. var gl = this._gl;
  15818. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15819. texture.isCube = true;
  15820. texture.url = rootUrl;
  15821. texture.generateMipMaps = !noMipmap;
  15822. texture._lodGenerationScale = lodScale;
  15823. texture._lodGenerationOffset = lodOffset;
  15824. if (!this._doNotHandleContextLost) {
  15825. texture._extension = forcedExtension;
  15826. texture._files = files;
  15827. }
  15828. var lastDot = rootUrl.lastIndexOf('.');
  15829. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15830. var loader = null;
  15831. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15832. var availableLoader = _a[_i];
  15833. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15834. loader = availableLoader;
  15835. break;
  15836. }
  15837. }
  15838. var onInternalError = function (request, exception) {
  15839. if (loader) {
  15840. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15841. if (fallbackUrl) {
  15842. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15843. }
  15844. }
  15845. if (onError && request) {
  15846. onError(request.status + " " + request.statusText, exception);
  15847. }
  15848. };
  15849. if (loader) {
  15850. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15851. var onloaddata = function (data) {
  15852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15853. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15854. };
  15855. if (files && files.length === 6) {
  15856. if (loader.supportCascades) {
  15857. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15858. }
  15859. else if (onError) {
  15860. onError("Textures type does not support cascades.");
  15861. }
  15862. }
  15863. else {
  15864. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15865. }
  15866. }
  15867. else {
  15868. if (!files) {
  15869. throw new Error("Cannot load cubemap because files were not defined");
  15870. }
  15871. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15872. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15873. var height = width;
  15874. _this._prepareWorkingCanvas();
  15875. if (!_this._workingCanvas || !_this._workingContext) {
  15876. return;
  15877. }
  15878. _this._workingCanvas.width = width;
  15879. _this._workingCanvas.height = height;
  15880. var faces = [
  15881. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15882. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15883. ];
  15884. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15885. _this._unpackFlipY(false);
  15886. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15887. for (var index = 0; index < faces.length; index++) {
  15888. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15889. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15890. }
  15891. if (!noMipmap) {
  15892. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15893. }
  15894. _this._setCubeMapTextureParams(!noMipmap);
  15895. texture.width = width;
  15896. texture.height = height;
  15897. texture.isReady = true;
  15898. if (format) {
  15899. texture.format = format;
  15900. }
  15901. texture.onLoadedObservable.notifyObservers(texture);
  15902. texture.onLoadedObservable.clear();
  15903. if (onLoad) {
  15904. onLoad();
  15905. }
  15906. }, files, onError);
  15907. }
  15908. this._internalTexturesCache.push(texture);
  15909. return texture;
  15910. };
  15911. /**
  15912. * @hidden
  15913. */
  15914. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15915. var gl = this._gl;
  15916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15921. // this.resetTextureCache();
  15922. };
  15923. /**
  15924. * Update a raw cube texture
  15925. * @param texture defines the texture to udpdate
  15926. * @param data defines the data to store
  15927. * @param format defines the data format
  15928. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15929. * @param invertY defines if data must be stored with Y axis inverted
  15930. * @param compression defines the compression used (null by default)
  15931. * @param level defines which level of the texture to update
  15932. */
  15933. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15934. if (compression === void 0) { compression = null; }
  15935. if (level === void 0) { level = 0; }
  15936. texture._bufferViewArray = data;
  15937. texture.format = format;
  15938. texture.type = type;
  15939. texture.invertY = invertY;
  15940. texture._compression = compression;
  15941. var gl = this._gl;
  15942. var textureType = this._getWebGLTextureType(type);
  15943. var internalFormat = this._getInternalFormat(format);
  15944. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15945. var needConversion = false;
  15946. if (internalFormat === gl.RGB) {
  15947. internalFormat = gl.RGBA;
  15948. needConversion = true;
  15949. }
  15950. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15951. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15952. if (texture.width % 4 !== 0) {
  15953. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15954. }
  15955. // Data are known to be in +X +Y +Z -X -Y -Z
  15956. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15957. var faceData = data[faceIndex];
  15958. if (compression) {
  15959. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15960. }
  15961. else {
  15962. if (needConversion) {
  15963. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15964. }
  15965. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15966. }
  15967. }
  15968. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15969. if (isPot && texture.generateMipMaps && level === 0) {
  15970. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15971. }
  15972. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15973. // this.resetTextureCache();
  15974. texture.isReady = true;
  15975. };
  15976. /**
  15977. * Creates a new raw cube texture
  15978. * @param data defines the array of data to use to create each face
  15979. * @param size defines the size of the textures
  15980. * @param format defines the format of the data
  15981. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15982. * @param generateMipMaps defines if the engine should generate the mip levels
  15983. * @param invertY defines if data must be stored with Y axis inverted
  15984. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15985. * @param compression defines the compression used (null by default)
  15986. * @returns the cube texture as an InternalTexture
  15987. */
  15988. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15989. if (compression === void 0) { compression = null; }
  15990. var gl = this._gl;
  15991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15992. texture.isCube = true;
  15993. texture.format = format;
  15994. texture.type = type;
  15995. if (!this._doNotHandleContextLost) {
  15996. texture._bufferViewArray = data;
  15997. }
  15998. var textureType = this._getWebGLTextureType(type);
  15999. var internalFormat = this._getInternalFormat(format);
  16000. if (internalFormat === gl.RGB) {
  16001. internalFormat = gl.RGBA;
  16002. }
  16003. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16004. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16005. generateMipMaps = false;
  16006. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16007. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16008. }
  16009. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16010. generateMipMaps = false;
  16011. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16012. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16013. }
  16014. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16015. generateMipMaps = false;
  16016. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16017. }
  16018. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16019. generateMipMaps = false;
  16020. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16021. }
  16022. var width = size;
  16023. var height = width;
  16024. texture.width = width;
  16025. texture.height = height;
  16026. // Double check on POT to generate Mips.
  16027. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16028. if (!isPot) {
  16029. generateMipMaps = false;
  16030. }
  16031. // Upload data if needed. The texture won't be ready until then.
  16032. if (data) {
  16033. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16034. }
  16035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16036. // Filters
  16037. if (data && generateMipMaps) {
  16038. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16039. }
  16040. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16045. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16046. texture.generateMipMaps = generateMipMaps;
  16047. return texture;
  16048. };
  16049. /**
  16050. * Creates a new raw cube texture from a specified url
  16051. * @param url defines the url where the data is located
  16052. * @param scene defines the current scene
  16053. * @param size defines the size of the textures
  16054. * @param format defines the format of the data
  16055. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16056. * @param noMipmap defines if the engine should avoid generating the mip levels
  16057. * @param callback defines a callback used to extract texture data from loaded data
  16058. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16059. * @param onLoad defines a callback called when texture is loaded
  16060. * @param onError defines a callback called if there is an error
  16061. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16062. * @param invertY defines if data must be stored with Y axis inverted
  16063. * @returns the cube texture as an InternalTexture
  16064. */
  16065. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16066. var _this = this;
  16067. if (onLoad === void 0) { onLoad = null; }
  16068. if (onError === void 0) { onError = null; }
  16069. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16070. if (invertY === void 0) { invertY = false; }
  16071. var gl = this._gl;
  16072. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16073. scene._addPendingData(texture);
  16074. texture.url = url;
  16075. this._internalTexturesCache.push(texture);
  16076. var onerror = function (request, exception) {
  16077. scene._removePendingData(texture);
  16078. if (onError && request) {
  16079. onError(request.status + " " + request.statusText, exception);
  16080. }
  16081. };
  16082. var internalCallback = function (data) {
  16083. var width = texture.width;
  16084. var faceDataArrays = callback(data);
  16085. if (!faceDataArrays) {
  16086. return;
  16087. }
  16088. if (mipmapGenerator) {
  16089. var textureType = _this._getWebGLTextureType(type);
  16090. var internalFormat = _this._getInternalFormat(format);
  16091. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16092. var needConversion = false;
  16093. if (internalFormat === gl.RGB) {
  16094. internalFormat = gl.RGBA;
  16095. needConversion = true;
  16096. }
  16097. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16098. _this._unpackFlipY(false);
  16099. var mipData = mipmapGenerator(faceDataArrays);
  16100. for (var level = 0; level < mipData.length; level++) {
  16101. var mipSize = width >> level;
  16102. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16103. var mipFaceData = mipData[level][faceIndex];
  16104. if (needConversion) {
  16105. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16106. }
  16107. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16108. }
  16109. }
  16110. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16111. }
  16112. else {
  16113. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16114. }
  16115. texture.isReady = true;
  16116. // this.resetTextureCache();
  16117. scene._removePendingData(texture);
  16118. if (onLoad) {
  16119. onLoad();
  16120. }
  16121. };
  16122. this._loadFile(url, function (data) {
  16123. internalCallback(data);
  16124. }, undefined, scene.database, true, onerror);
  16125. return texture;
  16126. };
  16127. ;
  16128. /**
  16129. * Update a raw 3D texture
  16130. * @param texture defines the texture to update
  16131. * @param data defines the data to store
  16132. * @param format defines the data format
  16133. * @param invertY defines if data must be stored with Y axis inverted
  16134. * @param compression defines the used compression (can be null)
  16135. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16136. */
  16137. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16138. if (compression === void 0) { compression = null; }
  16139. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16140. var internalType = this._getWebGLTextureType(textureType);
  16141. var internalFormat = this._getInternalFormat(format);
  16142. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16143. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16144. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16145. if (!this._doNotHandleContextLost) {
  16146. texture._bufferView = data;
  16147. texture.format = format;
  16148. texture.invertY = invertY;
  16149. texture._compression = compression;
  16150. }
  16151. if (texture.width % 4 !== 0) {
  16152. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16153. }
  16154. if (compression && data) {
  16155. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16156. }
  16157. else {
  16158. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16159. }
  16160. if (texture.generateMipMaps) {
  16161. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16162. }
  16163. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16164. // this.resetTextureCache();
  16165. texture.isReady = true;
  16166. };
  16167. /**
  16168. * Creates a new raw 3D texture
  16169. * @param data defines the data used to create the texture
  16170. * @param width defines the width of the texture
  16171. * @param height defines the height of the texture
  16172. * @param depth defines the depth of the texture
  16173. * @param format defines the format of the texture
  16174. * @param generateMipMaps defines if the engine must generate mip levels
  16175. * @param invertY defines if data must be stored with Y axis inverted
  16176. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16177. * @param compression defines the compressed used (can be null)
  16178. * @param textureType defines the compressed used (can be null)
  16179. * @returns a new raw 3D texture (stored in an InternalTexture)
  16180. */
  16181. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16182. if (compression === void 0) { compression = null; }
  16183. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16185. texture.baseWidth = width;
  16186. texture.baseHeight = height;
  16187. texture.baseDepth = depth;
  16188. texture.width = width;
  16189. texture.height = height;
  16190. texture.depth = depth;
  16191. texture.format = format;
  16192. texture.type = textureType;
  16193. texture.generateMipMaps = generateMipMaps;
  16194. texture.samplingMode = samplingMode;
  16195. texture.is3D = true;
  16196. if (!this._doNotHandleContextLost) {
  16197. texture._bufferView = data;
  16198. }
  16199. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16200. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16201. // Filters
  16202. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16204. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16205. if (generateMipMaps) {
  16206. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16207. }
  16208. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16209. this._internalTexturesCache.push(texture);
  16210. return texture;
  16211. };
  16212. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16213. var gl = this._gl;
  16214. if (!gl) {
  16215. return;
  16216. }
  16217. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16220. if (!noMipmap && !isCompressed) {
  16221. gl.generateMipmap(gl.TEXTURE_2D);
  16222. }
  16223. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16224. // this.resetTextureCache();
  16225. if (scene) {
  16226. scene._removePendingData(texture);
  16227. }
  16228. texture.onLoadedObservable.notifyObservers(texture);
  16229. texture.onLoadedObservable.clear();
  16230. };
  16231. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16232. var _this = this;
  16233. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16234. var maxTextureSize = this.getCaps().maxTextureSize;
  16235. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16236. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16237. var gl = this._gl;
  16238. if (!gl) {
  16239. return;
  16240. }
  16241. if (!texture._webGLTexture) {
  16242. // this.resetTextureCache();
  16243. if (scene) {
  16244. scene._removePendingData(texture);
  16245. }
  16246. return;
  16247. }
  16248. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16249. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16250. texture.baseWidth = width;
  16251. texture.baseHeight = height;
  16252. texture.width = potWidth;
  16253. texture.height = potHeight;
  16254. texture.isReady = true;
  16255. if (processFunction(potWidth, potHeight, function () {
  16256. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16257. })) {
  16258. // Returning as texture needs extra async steps
  16259. return;
  16260. }
  16261. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16262. };
  16263. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16264. // Create new RGBA data container.
  16265. var rgbaData;
  16266. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16267. rgbaData = new Float32Array(width * height * 4);
  16268. }
  16269. else {
  16270. rgbaData = new Uint32Array(width * height * 4);
  16271. }
  16272. // Convert each pixel.
  16273. for (var x = 0; x < width; x++) {
  16274. for (var y = 0; y < height; y++) {
  16275. var index = (y * width + x) * 3;
  16276. var newIndex = (y * width + x) * 4;
  16277. // Map Old Value to new value.
  16278. rgbaData[newIndex + 0] = rgbData[index + 0];
  16279. rgbaData[newIndex + 1] = rgbData[index + 1];
  16280. rgbaData[newIndex + 2] = rgbData[index + 2];
  16281. // Add fully opaque alpha channel.
  16282. rgbaData[newIndex + 3] = 1;
  16283. }
  16284. }
  16285. return rgbaData;
  16286. };
  16287. /** @hidden */
  16288. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16289. var gl = this._gl;
  16290. if (texture._framebuffer) {
  16291. gl.deleteFramebuffer(texture._framebuffer);
  16292. texture._framebuffer = null;
  16293. }
  16294. if (texture._depthStencilBuffer) {
  16295. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16296. texture._depthStencilBuffer = null;
  16297. }
  16298. if (texture._MSAAFramebuffer) {
  16299. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16300. texture._MSAAFramebuffer = null;
  16301. }
  16302. if (texture._MSAARenderBuffer) {
  16303. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16304. texture._MSAARenderBuffer = null;
  16305. }
  16306. };
  16307. /** @hidden */
  16308. Engine.prototype._releaseTexture = function (texture) {
  16309. var gl = this._gl;
  16310. this._releaseFramebufferObjects(texture);
  16311. gl.deleteTexture(texture._webGLTexture);
  16312. // Unbind channels
  16313. this.unbindAllTextures();
  16314. var index = this._internalTexturesCache.indexOf(texture);
  16315. if (index !== -1) {
  16316. this._internalTexturesCache.splice(index, 1);
  16317. }
  16318. // Integrated fixed lod samplers.
  16319. if (texture._lodTextureHigh) {
  16320. texture._lodTextureHigh.dispose();
  16321. }
  16322. if (texture._lodTextureMid) {
  16323. texture._lodTextureMid.dispose();
  16324. }
  16325. if (texture._lodTextureLow) {
  16326. texture._lodTextureLow.dispose();
  16327. }
  16328. // Set output texture of post process to null if the texture has been released/disposed
  16329. this.scenes.forEach(function (scene) {
  16330. scene.postProcesses.forEach(function (postProcess) {
  16331. if (postProcess._outputTexture == texture) {
  16332. postProcess._outputTexture = null;
  16333. }
  16334. });
  16335. scene.cameras.forEach(function (camera) {
  16336. camera._postProcesses.forEach(function (postProcess) {
  16337. if (postProcess) {
  16338. if (postProcess._outputTexture == texture) {
  16339. postProcess._outputTexture = null;
  16340. }
  16341. }
  16342. });
  16343. });
  16344. });
  16345. };
  16346. Engine.prototype.setProgram = function (program) {
  16347. if (this._currentProgram !== program) {
  16348. this._gl.useProgram(program);
  16349. this._currentProgram = program;
  16350. }
  16351. };
  16352. /**
  16353. * Binds an effect to the webGL context
  16354. * @param effect defines the effect to bind
  16355. */
  16356. Engine.prototype.bindSamplers = function (effect) {
  16357. this.setProgram(effect.getProgram());
  16358. var samplers = effect.getSamplers();
  16359. for (var index = 0; index < samplers.length; index++) {
  16360. var uniform = effect.getUniform(samplers[index]);
  16361. if (uniform) {
  16362. this._boundUniforms[index] = uniform;
  16363. }
  16364. }
  16365. this._currentEffect = null;
  16366. };
  16367. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16368. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16369. return;
  16370. }
  16371. // Remove
  16372. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16373. // Bind last to it
  16374. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16375. // Bind to dummy
  16376. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16377. };
  16378. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16379. if (!internalTexture) {
  16380. return -1;
  16381. }
  16382. internalTexture._initialSlot = channel;
  16383. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16384. if (channel !== internalTexture._designatedSlot) {
  16385. this._textureCollisions.addCount(1, false);
  16386. }
  16387. }
  16388. else {
  16389. if (channel !== internalTexture._designatedSlot) {
  16390. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16391. return internalTexture._designatedSlot;
  16392. }
  16393. else {
  16394. // No slot for this texture, let's pick a new one (if we find a free slot)
  16395. if (this._nextFreeTextureSlots.length) {
  16396. return this._nextFreeTextureSlots[0];
  16397. }
  16398. // We need to recycle the oldest bound texture, sorry.
  16399. this._textureCollisions.addCount(1, false);
  16400. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16401. }
  16402. }
  16403. }
  16404. return channel;
  16405. };
  16406. Engine.prototype._linkTrackers = function (previous, next) {
  16407. previous.next = next;
  16408. next.previous = previous;
  16409. };
  16410. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16411. var currentSlot = internalTexture._designatedSlot;
  16412. if (currentSlot === -1) {
  16413. return -1;
  16414. }
  16415. internalTexture._designatedSlot = -1;
  16416. if (this.disableTextureBindingOptimization) {
  16417. return -1;
  16418. }
  16419. // Remove from bound list
  16420. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16421. // Free the slot
  16422. this._boundTexturesCache[currentSlot] = null;
  16423. this._nextFreeTextureSlots.push(currentSlot);
  16424. return currentSlot;
  16425. };
  16426. Engine.prototype._activateCurrentTexture = function () {
  16427. if (this._currentTextureChannel !== this._activeChannel) {
  16428. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16429. this._currentTextureChannel = this._activeChannel;
  16430. }
  16431. };
  16432. /** @hidden */
  16433. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16434. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16435. if (force === void 0) { force = false; }
  16436. var wasPreviouslyBound = false;
  16437. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16438. this._activeChannel = texture._designatedSlot;
  16439. }
  16440. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16441. var isTextureForRendering = texture && texture._initialSlot > -1;
  16442. if (currentTextureBound !== texture || force) {
  16443. if (currentTextureBound) {
  16444. this._removeDesignatedSlot(currentTextureBound);
  16445. }
  16446. this._activateCurrentTexture();
  16447. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16448. this._boundTexturesCache[this._activeChannel] = texture;
  16449. if (texture) {
  16450. if (!this.disableTextureBindingOptimization) {
  16451. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16452. if (slotIndex > -1) {
  16453. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16454. }
  16455. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16456. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16457. }
  16458. texture._designatedSlot = this._activeChannel;
  16459. }
  16460. }
  16461. else if (forTextureDataUpdate) {
  16462. wasPreviouslyBound = true;
  16463. this._activateCurrentTexture();
  16464. }
  16465. if (isTextureForRendering && !forTextureDataUpdate) {
  16466. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16467. }
  16468. return wasPreviouslyBound;
  16469. };
  16470. /** @hidden */
  16471. Engine.prototype._bindTexture = function (channel, texture) {
  16472. if (channel < 0) {
  16473. return;
  16474. }
  16475. if (texture) {
  16476. channel = this._getCorrectTextureChannel(channel, texture);
  16477. }
  16478. this._activeChannel = channel;
  16479. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16480. };
  16481. /**
  16482. * Sets a texture to the webGL context from a postprocess
  16483. * @param channel defines the channel to use
  16484. * @param postProcess defines the source postprocess
  16485. */
  16486. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16487. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16488. };
  16489. /**
  16490. * Binds the output of the passed in post process to the texture channel specified
  16491. * @param channel The channel the texture should be bound to
  16492. * @param postProcess The post process which's output should be bound
  16493. */
  16494. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16495. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16496. };
  16497. /**
  16498. * Unbind all textures from the webGL context
  16499. */
  16500. Engine.prototype.unbindAllTextures = function () {
  16501. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16502. this._activeChannel = channel;
  16503. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16504. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16505. if (this.webGLVersion > 1) {
  16506. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16507. }
  16508. }
  16509. };
  16510. /**
  16511. * Sets a texture to the according uniform.
  16512. * @param channel The texture channel
  16513. * @param uniform The uniform to set
  16514. * @param texture The texture to apply
  16515. */
  16516. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16517. if (channel < 0) {
  16518. return;
  16519. }
  16520. if (uniform) {
  16521. this._boundUniforms[channel] = uniform;
  16522. }
  16523. this._setTexture(channel, texture);
  16524. };
  16525. /**
  16526. * Sets a depth stencil texture from a render target to the according uniform.
  16527. * @param channel The texture channel
  16528. * @param uniform The uniform to set
  16529. * @param texture The render target texture containing the depth stencil texture to apply
  16530. */
  16531. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16532. if (channel < 0) {
  16533. return;
  16534. }
  16535. if (uniform) {
  16536. this._boundUniforms[channel] = uniform;
  16537. }
  16538. if (!texture || !texture.depthStencilTexture) {
  16539. this._setTexture(channel, null);
  16540. }
  16541. else {
  16542. this._setTexture(channel, texture, false, true);
  16543. }
  16544. };
  16545. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16546. var uniform = this._boundUniforms[sourceSlot];
  16547. if (uniform._currentState === destination) {
  16548. return;
  16549. }
  16550. this._gl.uniform1i(uniform, destination);
  16551. uniform._currentState = destination;
  16552. };
  16553. Engine.prototype._getTextureWrapMode = function (mode) {
  16554. switch (mode) {
  16555. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16556. return this._gl.REPEAT;
  16557. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16558. return this._gl.CLAMP_TO_EDGE;
  16559. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16560. return this._gl.MIRRORED_REPEAT;
  16561. }
  16562. return this._gl.REPEAT;
  16563. };
  16564. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16565. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16566. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16567. // Not ready?
  16568. if (!texture) {
  16569. if (this._boundTexturesCache[channel] != null) {
  16570. this._activeChannel = channel;
  16571. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16572. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16573. if (this.webGLVersion > 1) {
  16574. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16575. }
  16576. }
  16577. return false;
  16578. }
  16579. // Video
  16580. if (texture.video) {
  16581. this._activeChannel = channel;
  16582. texture.update();
  16583. }
  16584. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16585. texture.delayLoad();
  16586. return false;
  16587. }
  16588. var internalTexture;
  16589. if (depthStencilTexture) {
  16590. internalTexture = texture.depthStencilTexture;
  16591. }
  16592. else if (texture.isReady()) {
  16593. internalTexture = texture.getInternalTexture();
  16594. }
  16595. else if (texture.isCube) {
  16596. internalTexture = this.emptyCubeTexture;
  16597. }
  16598. else if (texture.is3D) {
  16599. internalTexture = this.emptyTexture3D;
  16600. }
  16601. else {
  16602. internalTexture = this.emptyTexture;
  16603. }
  16604. if (!isPartOfTextureArray) {
  16605. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16606. }
  16607. var needToBind = true;
  16608. if (this._boundTexturesCache[channel] === internalTexture) {
  16609. this._moveBoundTextureOnTop(internalTexture);
  16610. if (!isPartOfTextureArray) {
  16611. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16612. }
  16613. needToBind = false;
  16614. }
  16615. this._activeChannel = channel;
  16616. if (internalTexture && internalTexture.is3D) {
  16617. if (needToBind) {
  16618. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16619. }
  16620. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16621. internalTexture._cachedWrapU = texture.wrapU;
  16622. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16623. }
  16624. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16625. internalTexture._cachedWrapV = texture.wrapV;
  16626. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16627. }
  16628. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16629. internalTexture._cachedWrapR = texture.wrapR;
  16630. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16631. }
  16632. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16633. }
  16634. else if (internalTexture && internalTexture.isCube) {
  16635. if (needToBind) {
  16636. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16637. }
  16638. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16639. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16640. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16641. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16642. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16643. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16644. }
  16645. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16646. }
  16647. else {
  16648. if (needToBind) {
  16649. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16650. }
  16651. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16652. internalTexture._cachedWrapU = texture.wrapU;
  16653. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16654. }
  16655. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16656. internalTexture._cachedWrapV = texture.wrapV;
  16657. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16658. }
  16659. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16660. }
  16661. return true;
  16662. };
  16663. /**
  16664. * Sets an array of texture to the webGL context
  16665. * @param channel defines the channel where the texture array must be set
  16666. * @param uniform defines the associated uniform location
  16667. * @param textures defines the array of textures to bind
  16668. */
  16669. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16670. if (channel < 0 || !uniform) {
  16671. return;
  16672. }
  16673. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16674. this._textureUnits = new Int32Array(textures.length);
  16675. }
  16676. for (var i = 0; i < textures.length; i++) {
  16677. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16678. }
  16679. this._gl.uniform1iv(uniform, this._textureUnits);
  16680. for (var index = 0; index < textures.length; index++) {
  16681. this._setTexture(this._textureUnits[index], textures[index], true);
  16682. }
  16683. };
  16684. /** @hidden */
  16685. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16686. var internalTexture = texture.getInternalTexture();
  16687. if (!internalTexture) {
  16688. return;
  16689. }
  16690. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16691. var value = texture.anisotropicFilteringLevel;
  16692. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16693. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16694. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16695. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16696. }
  16697. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16698. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16699. internalTexture._cachedAnisotropicFilteringLevel = value;
  16700. }
  16701. };
  16702. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16703. this._bindTextureDirectly(target, texture, true, true);
  16704. this._gl.texParameterf(target, parameter, value);
  16705. };
  16706. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16707. if (texture) {
  16708. this._bindTextureDirectly(target, texture, true, true);
  16709. }
  16710. this._gl.texParameteri(target, parameter, value);
  16711. };
  16712. /**
  16713. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16714. * @param x defines the x coordinate of the rectangle where pixels must be read
  16715. * @param y defines the y coordinate of the rectangle where pixels must be read
  16716. * @param width defines the width of the rectangle where pixels must be read
  16717. * @param height defines the height of the rectangle where pixels must be read
  16718. * @returns a Uint8Array containing RGBA colors
  16719. */
  16720. Engine.prototype.readPixels = function (x, y, width, height) {
  16721. var data = new Uint8Array(height * width * 4);
  16722. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16723. return data;
  16724. };
  16725. /**
  16726. * Add an externaly attached data from its key.
  16727. * This method call will fail and return false, if such key already exists.
  16728. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16729. * @param key the unique key that identifies the data
  16730. * @param data the data object to associate to the key for this Engine instance
  16731. * @return true if no such key were already present and the data was added successfully, false otherwise
  16732. */
  16733. Engine.prototype.addExternalData = function (key, data) {
  16734. if (!this._externalData) {
  16735. this._externalData = new BABYLON.StringDictionary();
  16736. }
  16737. return this._externalData.add(key, data);
  16738. };
  16739. /**
  16740. * Get an externaly attached data from its key
  16741. * @param key the unique key that identifies the data
  16742. * @return the associated data, if present (can be null), or undefined if not present
  16743. */
  16744. Engine.prototype.getExternalData = function (key) {
  16745. if (!this._externalData) {
  16746. this._externalData = new BABYLON.StringDictionary();
  16747. }
  16748. return this._externalData.get(key);
  16749. };
  16750. /**
  16751. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16752. * @param key the unique key that identifies the data
  16753. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16754. * @return the associated data, can be null if the factory returned null.
  16755. */
  16756. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16757. if (!this._externalData) {
  16758. this._externalData = new BABYLON.StringDictionary();
  16759. }
  16760. return this._externalData.getOrAddWithFactory(key, factory);
  16761. };
  16762. /**
  16763. * Remove an externaly attached data from the Engine instance
  16764. * @param key the unique key that identifies the data
  16765. * @return true if the data was successfully removed, false if it doesn't exist
  16766. */
  16767. Engine.prototype.removeExternalData = function (key) {
  16768. if (!this._externalData) {
  16769. this._externalData = new BABYLON.StringDictionary();
  16770. }
  16771. return this._externalData.remove(key);
  16772. };
  16773. /**
  16774. * Unbind all vertex attributes from the webGL context
  16775. */
  16776. Engine.prototype.unbindAllAttributes = function () {
  16777. if (this._mustWipeVertexAttributes) {
  16778. this._mustWipeVertexAttributes = false;
  16779. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16780. this._gl.disableVertexAttribArray(i);
  16781. this._vertexAttribArraysEnabled[i] = false;
  16782. this._currentBufferPointers[i].active = false;
  16783. }
  16784. return;
  16785. }
  16786. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16787. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16788. continue;
  16789. }
  16790. this._gl.disableVertexAttribArray(i);
  16791. this._vertexAttribArraysEnabled[i] = false;
  16792. this._currentBufferPointers[i].active = false;
  16793. }
  16794. };
  16795. /**
  16796. * 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
  16797. */
  16798. Engine.prototype.releaseEffects = function () {
  16799. for (var name in this._compiledEffects) {
  16800. this._deleteProgram(this._compiledEffects[name]._program);
  16801. }
  16802. this._compiledEffects = {};
  16803. };
  16804. /**
  16805. * Dispose and release all associated resources
  16806. */
  16807. Engine.prototype.dispose = function () {
  16808. this.hideLoadingUI();
  16809. this.stopRenderLoop();
  16810. // Release postProcesses
  16811. while (this.postProcesses.length) {
  16812. this.postProcesses[0].dispose();
  16813. }
  16814. // Empty texture
  16815. if (this._emptyTexture) {
  16816. this._releaseTexture(this._emptyTexture);
  16817. this._emptyTexture = null;
  16818. }
  16819. if (this._emptyCubeTexture) {
  16820. this._releaseTexture(this._emptyCubeTexture);
  16821. this._emptyCubeTexture = null;
  16822. }
  16823. // Rescale PP
  16824. if (this._rescalePostProcess) {
  16825. this._rescalePostProcess.dispose();
  16826. }
  16827. // Release scenes
  16828. while (this.scenes.length) {
  16829. this.scenes[0].dispose();
  16830. }
  16831. // Release audio engine
  16832. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16833. Engine.audioEngine.dispose();
  16834. }
  16835. // Release effects
  16836. this.releaseEffects();
  16837. // Unbind
  16838. this.unbindAllAttributes();
  16839. this._boundUniforms = [];
  16840. if (this._dummyFramebuffer) {
  16841. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16842. }
  16843. //WebVR
  16844. this.disableVR();
  16845. // Events
  16846. if (BABYLON.Tools.IsWindowObjectExist()) {
  16847. window.removeEventListener("blur", this._onBlur);
  16848. window.removeEventListener("focus", this._onFocus);
  16849. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16850. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16851. if (this._renderingCanvas) {
  16852. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16853. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16854. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16855. if (!this._doNotHandleContextLost) {
  16856. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16857. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16858. }
  16859. }
  16860. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16861. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16862. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16863. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16864. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16865. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16866. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16867. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16868. if (this._onVrDisplayConnect) {
  16869. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16870. if (this._onVrDisplayDisconnect) {
  16871. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16872. }
  16873. if (this._onVrDisplayPresentChange) {
  16874. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16875. }
  16876. this._onVrDisplayConnect = null;
  16877. this._onVrDisplayDisconnect = null;
  16878. }
  16879. }
  16880. // Remove from Instances
  16881. var index = Engine.Instances.indexOf(this);
  16882. if (index >= 0) {
  16883. Engine.Instances.splice(index, 1);
  16884. }
  16885. this._workingCanvas = null;
  16886. this._workingContext = null;
  16887. this._currentBufferPointers = [];
  16888. this._renderingCanvas = null;
  16889. this._currentProgram = null;
  16890. this._bindedRenderFunction = null;
  16891. this.onResizeObservable.clear();
  16892. this.onCanvasBlurObservable.clear();
  16893. this.onCanvasFocusObservable.clear();
  16894. this.onCanvasPointerOutObservable.clear();
  16895. this.onBeginFrameObservable.clear();
  16896. this.onEndFrameObservable.clear();
  16897. BABYLON.Effect.ResetCache();
  16898. // Abort active requests
  16899. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16900. var request = _a[_i];
  16901. request.abort();
  16902. }
  16903. };
  16904. // Loading screen
  16905. /**
  16906. * Display the loading screen
  16907. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16908. */
  16909. Engine.prototype.displayLoadingUI = function () {
  16910. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16911. return;
  16912. }
  16913. var loadingScreen = this.loadingScreen;
  16914. if (loadingScreen) {
  16915. loadingScreen.displayLoadingUI();
  16916. }
  16917. };
  16918. /**
  16919. * Hide the loading screen
  16920. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16921. */
  16922. Engine.prototype.hideLoadingUI = function () {
  16923. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16924. return;
  16925. }
  16926. var loadingScreen = this.loadingScreen;
  16927. if (loadingScreen) {
  16928. loadingScreen.hideLoadingUI();
  16929. }
  16930. };
  16931. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16932. /**
  16933. * Gets the current loading screen object
  16934. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16935. */
  16936. get: function () {
  16937. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16938. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16939. return this._loadingScreen;
  16940. },
  16941. /**
  16942. * Sets the current loading screen object
  16943. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16944. */
  16945. set: function (loadingScreen) {
  16946. this._loadingScreen = loadingScreen;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16952. /**
  16953. * Sets the current loading screen text
  16954. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16955. */
  16956. set: function (text) {
  16957. this.loadingScreen.loadingUIText = text;
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16963. /**
  16964. * Sets the current loading screen background color
  16965. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16966. */
  16967. set: function (color) {
  16968. this.loadingScreen.loadingUIBackgroundColor = color;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. /**
  16974. * Attach a new callback raised when context lost event is fired
  16975. * @param callback defines the callback to call
  16976. */
  16977. Engine.prototype.attachContextLostEvent = function (callback) {
  16978. if (this._renderingCanvas) {
  16979. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16980. }
  16981. };
  16982. /**
  16983. * Attach a new callback raised when context restored event is fired
  16984. * @param callback defines the callback to call
  16985. */
  16986. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16987. if (this._renderingCanvas) {
  16988. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16989. }
  16990. };
  16991. /**
  16992. * Gets the source code of the vertex shader associated with a specific webGL program
  16993. * @param program defines the program to use
  16994. * @returns a string containing the source code of the vertex shader associated with the program
  16995. */
  16996. Engine.prototype.getVertexShaderSource = function (program) {
  16997. var shaders = this._gl.getAttachedShaders(program);
  16998. if (!shaders) {
  16999. return null;
  17000. }
  17001. return this._gl.getShaderSource(shaders[0]);
  17002. };
  17003. /**
  17004. * Gets the source code of the fragment shader associated with a specific webGL program
  17005. * @param program defines the program to use
  17006. * @returns a string containing the source code of the fragment shader associated with the program
  17007. */
  17008. Engine.prototype.getFragmentShaderSource = function (program) {
  17009. var shaders = this._gl.getAttachedShaders(program);
  17010. if (!shaders) {
  17011. return null;
  17012. }
  17013. return this._gl.getShaderSource(shaders[1]);
  17014. };
  17015. /**
  17016. * Get the current error code of the webGL context
  17017. * @returns the error code
  17018. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17019. */
  17020. Engine.prototype.getError = function () {
  17021. return this._gl.getError();
  17022. };
  17023. // FPS
  17024. /**
  17025. * Gets the current framerate
  17026. * @returns a number representing the framerate
  17027. */
  17028. Engine.prototype.getFps = function () {
  17029. return this._fps;
  17030. };
  17031. /**
  17032. * Gets the time spent between current and previous frame
  17033. * @returns a number representing the delta time in ms
  17034. */
  17035. Engine.prototype.getDeltaTime = function () {
  17036. return this._deltaTime;
  17037. };
  17038. Engine.prototype._measureFps = function () {
  17039. this._performanceMonitor.sampleFrame();
  17040. this._fps = this._performanceMonitor.averageFPS;
  17041. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17042. };
  17043. /** @hidden */
  17044. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17045. if (faceIndex === void 0) { faceIndex = -1; }
  17046. if (level === void 0) { level = 0; }
  17047. if (buffer === void 0) { buffer = null; }
  17048. var gl = this._gl;
  17049. if (!this._dummyFramebuffer) {
  17050. var dummy = gl.createFramebuffer();
  17051. if (!dummy) {
  17052. throw new Error("Unable to create dummy framebuffer");
  17053. }
  17054. this._dummyFramebuffer = dummy;
  17055. }
  17056. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17057. if (faceIndex > -1) {
  17058. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17059. }
  17060. else {
  17061. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17062. }
  17063. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17064. switch (readType) {
  17065. case gl.UNSIGNED_BYTE:
  17066. if (!buffer) {
  17067. buffer = new Uint8Array(4 * width * height);
  17068. }
  17069. readType = gl.UNSIGNED_BYTE;
  17070. break;
  17071. default:
  17072. if (!buffer) {
  17073. buffer = new Float32Array(4 * width * height);
  17074. }
  17075. readType = gl.FLOAT;
  17076. break;
  17077. }
  17078. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17079. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17080. return buffer;
  17081. };
  17082. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17083. if (this._webGLVersion > 1) {
  17084. return this._caps.colorBufferFloat;
  17085. }
  17086. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17087. };
  17088. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17089. if (this._webGLVersion > 1) {
  17090. return this._caps.colorBufferFloat;
  17091. }
  17092. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17093. };
  17094. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17095. Engine.prototype._canRenderToFramebuffer = function (type) {
  17096. var gl = this._gl;
  17097. //clear existing errors
  17098. while (gl.getError() !== gl.NO_ERROR) { }
  17099. var successful = true;
  17100. var texture = gl.createTexture();
  17101. gl.bindTexture(gl.TEXTURE_2D, texture);
  17102. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17105. var fb = gl.createFramebuffer();
  17106. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17107. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17108. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17109. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17110. successful = successful && (gl.getError() === gl.NO_ERROR);
  17111. //try render by clearing frame buffer's color buffer
  17112. if (successful) {
  17113. gl.clear(gl.COLOR_BUFFER_BIT);
  17114. successful = successful && (gl.getError() === gl.NO_ERROR);
  17115. }
  17116. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17117. if (successful) {
  17118. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17119. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17120. var readFormat = gl.RGBA;
  17121. var readType = gl.UNSIGNED_BYTE;
  17122. var buffer = new Uint8Array(4);
  17123. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17124. successful = successful && (gl.getError() === gl.NO_ERROR);
  17125. }
  17126. //clean up
  17127. gl.deleteTexture(texture);
  17128. gl.deleteFramebuffer(fb);
  17129. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17130. //clear accumulated errors
  17131. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17132. return successful;
  17133. };
  17134. /** @hidden */
  17135. Engine.prototype._getWebGLTextureType = function (type) {
  17136. if (this._webGLVersion === 1) {
  17137. switch (type) {
  17138. case Engine.TEXTURETYPE_FLOAT:
  17139. return this._gl.FLOAT;
  17140. case Engine.TEXTURETYPE_HALF_FLOAT:
  17141. return this._gl.HALF_FLOAT_OES;
  17142. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17143. return this._gl.UNSIGNED_BYTE;
  17144. }
  17145. return this._gl.UNSIGNED_BYTE;
  17146. }
  17147. switch (type) {
  17148. case Engine.TEXTURETYPE_BYTE:
  17149. return this._gl.BYTE;
  17150. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17151. return this._gl.UNSIGNED_BYTE;
  17152. case Engine.TEXTURETYPE_SHORT:
  17153. return this._gl.SHORT;
  17154. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17155. return this._gl.UNSIGNED_SHORT;
  17156. case Engine.TEXTURETYPE_INT:
  17157. return this._gl.INT;
  17158. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17159. return this._gl.UNSIGNED_INT;
  17160. case Engine.TEXTURETYPE_FLOAT:
  17161. return this._gl.FLOAT;
  17162. case Engine.TEXTURETYPE_HALF_FLOAT:
  17163. return this._gl.HALF_FLOAT;
  17164. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17165. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17166. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17167. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17168. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17169. return this._gl.UNSIGNED_SHORT_5_6_5;
  17170. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17171. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17172. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17173. return this._gl.UNSIGNED_INT_24_8;
  17174. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17175. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17176. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17177. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17178. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17179. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17180. }
  17181. return this._gl.UNSIGNED_BYTE;
  17182. };
  17183. ;
  17184. Engine.prototype._getInternalFormat = function (format) {
  17185. var internalFormat = this._gl.RGBA;
  17186. switch (format) {
  17187. case Engine.TEXTUREFORMAT_ALPHA:
  17188. internalFormat = this._gl.ALPHA;
  17189. break;
  17190. case Engine.TEXTUREFORMAT_LUMINANCE:
  17191. internalFormat = this._gl.LUMINANCE;
  17192. break;
  17193. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17194. internalFormat = this._gl.LUMINANCE_ALPHA;
  17195. break;
  17196. case Engine.TEXTUREFORMAT_RED:
  17197. internalFormat = this._gl.RED;
  17198. break;
  17199. case Engine.TEXTUREFORMAT_RG:
  17200. internalFormat = this._gl.RG;
  17201. break;
  17202. case Engine.TEXTUREFORMAT_RGB:
  17203. internalFormat = this._gl.RGB;
  17204. break;
  17205. case Engine.TEXTUREFORMAT_RGBA:
  17206. internalFormat = this._gl.RGBA;
  17207. break;
  17208. }
  17209. if (this._webGLVersion > 1) {
  17210. switch (format) {
  17211. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17212. internalFormat = this._gl.RED_INTEGER;
  17213. break;
  17214. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17215. internalFormat = this._gl.RG_INTEGER;
  17216. break;
  17217. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17218. internalFormat = this._gl.RGB_INTEGER;
  17219. break;
  17220. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17221. internalFormat = this._gl.RGBA_INTEGER;
  17222. break;
  17223. }
  17224. }
  17225. return internalFormat;
  17226. };
  17227. /** @hidden */
  17228. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17229. if (this._webGLVersion === 1) {
  17230. if (format !== undefined) {
  17231. switch (format) {
  17232. case Engine.TEXTUREFORMAT_ALPHA:
  17233. return this._gl.ALPHA;
  17234. case Engine.TEXTUREFORMAT_LUMINANCE:
  17235. return this._gl.LUMINANCE;
  17236. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17237. return this._gl.LUMINANCE_ALPHA;
  17238. }
  17239. }
  17240. return this._gl.RGBA;
  17241. }
  17242. switch (type) {
  17243. case Engine.TEXTURETYPE_BYTE:
  17244. switch (format) {
  17245. case Engine.TEXTUREFORMAT_RED:
  17246. return this._gl.R8_SNORM;
  17247. case Engine.TEXTUREFORMAT_RG:
  17248. return this._gl.RG8_SNORM;
  17249. case Engine.TEXTUREFORMAT_RGB:
  17250. return this._gl.RGB8_SNORM;
  17251. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17252. return this._gl.R8I;
  17253. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17254. return this._gl.RG8I;
  17255. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17256. return this._gl.RGB8I;
  17257. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17258. return this._gl.RGBA8I;
  17259. default:
  17260. return this._gl.RGBA8_SNORM;
  17261. }
  17262. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17263. switch (format) {
  17264. case Engine.TEXTUREFORMAT_RED:
  17265. return this._gl.R8;
  17266. case Engine.TEXTUREFORMAT_RG:
  17267. return this._gl.RG8;
  17268. case Engine.TEXTUREFORMAT_RGB:
  17269. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17270. case Engine.TEXTUREFORMAT_RGBA:
  17271. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17272. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17273. return this._gl.R8UI;
  17274. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17275. return this._gl.RG8UI;
  17276. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17277. return this._gl.RGB8UI;
  17278. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17279. return this._gl.RGBA8UI;
  17280. default:
  17281. return this._gl.RGBA8;
  17282. }
  17283. case Engine.TEXTURETYPE_SHORT:
  17284. switch (format) {
  17285. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17286. return this._gl.R16I;
  17287. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17288. return this._gl.RG16I;
  17289. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17290. return this._gl.RGB16I;
  17291. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17292. return this._gl.RGBA16I;
  17293. default:
  17294. return this._gl.RGBA16I;
  17295. }
  17296. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17297. switch (format) {
  17298. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17299. return this._gl.R16UI;
  17300. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17301. return this._gl.RG16UI;
  17302. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17303. return this._gl.RGB16UI;
  17304. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17305. return this._gl.RGBA16UI;
  17306. default:
  17307. return this._gl.RGBA16UI;
  17308. }
  17309. case Engine.TEXTURETYPE_INT:
  17310. switch (format) {
  17311. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17312. return this._gl.R32I;
  17313. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17314. return this._gl.RG32I;
  17315. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17316. return this._gl.RGB32I;
  17317. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17318. return this._gl.RGBA32I;
  17319. default:
  17320. return this._gl.RGBA32I;
  17321. }
  17322. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17323. switch (format) {
  17324. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17325. return this._gl.R32UI;
  17326. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17327. return this._gl.RG32UI;
  17328. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17329. return this._gl.RGB32UI;
  17330. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17331. return this._gl.RGBA32UI;
  17332. default:
  17333. return this._gl.RGBA32UI;
  17334. }
  17335. case Engine.TEXTURETYPE_FLOAT:
  17336. switch (format) {
  17337. case Engine.TEXTUREFORMAT_RED:
  17338. return this._gl.R32F; // By default. Other possibility is R16F.
  17339. case Engine.TEXTUREFORMAT_RG:
  17340. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17341. case Engine.TEXTUREFORMAT_RGB:
  17342. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17343. case Engine.TEXTUREFORMAT_RGBA:
  17344. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17345. default:
  17346. return this._gl.RGBA32F;
  17347. }
  17348. case Engine.TEXTURETYPE_HALF_FLOAT:
  17349. switch (format) {
  17350. case Engine.TEXTUREFORMAT_RED:
  17351. return this._gl.R16F;
  17352. case Engine.TEXTUREFORMAT_RG:
  17353. return this._gl.RG16F;
  17354. case Engine.TEXTUREFORMAT_RGB:
  17355. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17356. case Engine.TEXTUREFORMAT_RGBA:
  17357. return this._gl.RGBA16F;
  17358. default:
  17359. return this._gl.RGBA16F;
  17360. }
  17361. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17362. return this._gl.RGB565;
  17363. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17364. return this._gl.R11F_G11F_B10F;
  17365. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17366. return this._gl.RGB9_E5;
  17367. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17368. return this._gl.RGBA4;
  17369. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17370. return this._gl.RGB5_A1;
  17371. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17372. switch (format) {
  17373. case Engine.TEXTUREFORMAT_RGBA:
  17374. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17375. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17376. return this._gl.RGB10_A2UI;
  17377. default:
  17378. return this._gl.RGB10_A2;
  17379. }
  17380. }
  17381. return this._gl.RGBA8;
  17382. };
  17383. ;
  17384. /** @hidden */
  17385. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17386. if (type === Engine.TEXTURETYPE_FLOAT) {
  17387. return this._gl.RGBA32F;
  17388. }
  17389. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17390. return this._gl.RGBA16F;
  17391. }
  17392. return this._gl.RGBA8;
  17393. };
  17394. ;
  17395. /** @hidden */
  17396. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17397. var _this = this;
  17398. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17399. this._activeRequests.push(request);
  17400. request.onCompleteObservable.add(function (request) {
  17401. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17402. });
  17403. return request;
  17404. };
  17405. /** @hidden */
  17406. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17407. var _this = this;
  17408. return new Promise(function (resolve, reject) {
  17409. _this._loadFile(url, function (data) {
  17410. resolve(data);
  17411. }, undefined, database, useArrayBuffer, function (request, exception) {
  17412. reject(exception);
  17413. });
  17414. });
  17415. };
  17416. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17417. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17418. var onload = function (data) {
  17419. loadedFiles[index] = data;
  17420. loadedFiles._internalCount++;
  17421. if (loadedFiles._internalCount === 6) {
  17422. onfinish(loadedFiles);
  17423. }
  17424. };
  17425. var onerror = function (request, exception) {
  17426. if (onErrorCallBack && request) {
  17427. onErrorCallBack(request.status + " " + request.statusText, exception);
  17428. }
  17429. };
  17430. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17431. };
  17432. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17433. if (onError === void 0) { onError = null; }
  17434. var loadedFiles = [];
  17435. loadedFiles._internalCount = 0;
  17436. for (var index = 0; index < 6; index++) {
  17437. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17438. }
  17439. };
  17440. // Statics
  17441. /**
  17442. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17443. * @returns true if the engine can be created
  17444. * @ignorenaming
  17445. */
  17446. Engine.isSupported = function () {
  17447. try {
  17448. var tempcanvas = document.createElement("canvas");
  17449. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17450. return gl != null && !!window.WebGLRenderingContext;
  17451. }
  17452. catch (e) {
  17453. return false;
  17454. }
  17455. };
  17456. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17457. Engine.ExceptionList = [
  17458. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17459. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17460. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17461. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17462. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17463. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17464. ];
  17465. /** Gets the list of created engines */
  17466. Engine.Instances = new Array();
  17467. /**
  17468. * Hidden
  17469. */
  17470. Engine._TextureLoaders = [];
  17471. // Const statics
  17472. /** Defines that alpha blending is disabled */
  17473. Engine.ALPHA_DISABLE = 0;
  17474. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17475. Engine.ALPHA_ADD = 1;
  17476. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17477. Engine.ALPHA_COMBINE = 2;
  17478. /** Defines that alpha blending to DEST - SRC * DEST */
  17479. Engine.ALPHA_SUBTRACT = 3;
  17480. /** Defines that alpha blending to SRC * DEST */
  17481. Engine.ALPHA_MULTIPLY = 4;
  17482. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17483. Engine.ALPHA_MAXIMIZED = 5;
  17484. /** Defines that alpha blending to SRC + DEST */
  17485. Engine.ALPHA_ONEONE = 6;
  17486. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17487. Engine.ALPHA_PREMULTIPLIED = 7;
  17488. /**
  17489. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17490. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17491. */
  17492. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17493. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17494. Engine.ALPHA_INTERPOLATE = 9;
  17495. /**
  17496. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17497. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17498. */
  17499. Engine.ALPHA_SCREENMODE = 10;
  17500. /** Defines that the ressource is not delayed*/
  17501. Engine.DELAYLOADSTATE_NONE = 0;
  17502. /** Defines that the ressource was successfully delay loaded */
  17503. Engine.DELAYLOADSTATE_LOADED = 1;
  17504. /** Defines that the ressource is currently delay loading */
  17505. Engine.DELAYLOADSTATE_LOADING = 2;
  17506. /** Defines that the ressource is delayed and has not started loading */
  17507. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17508. // Depht or Stencil test Constants.
  17509. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17510. Engine.NEVER = 0x0200;
  17511. /** 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 */
  17512. Engine.ALWAYS = 0x0207;
  17513. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17514. Engine.LESS = 0x0201;
  17515. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17516. Engine.EQUAL = 0x0202;
  17517. /** 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 */
  17518. Engine.LEQUAL = 0x0203;
  17519. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17520. Engine.GREATER = 0x0204;
  17521. /** 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 */
  17522. Engine.GEQUAL = 0x0206;
  17523. /** 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 */
  17524. Engine.NOTEQUAL = 0x0205;
  17525. // Stencil Actions Constants.
  17526. /** Passed to stencilOperation to specify that stencil value must be kept */
  17527. Engine.KEEP = 0x1E00;
  17528. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17529. Engine.REPLACE = 0x1E01;
  17530. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17531. Engine.INCR = 0x1E02;
  17532. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17533. Engine.DECR = 0x1E03;
  17534. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17535. Engine.INVERT = 0x150A;
  17536. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17537. Engine.INCR_WRAP = 0x8507;
  17538. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17539. Engine.DECR_WRAP = 0x8508;
  17540. /** Texture is not repeating outside of 0..1 UVs */
  17541. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17542. /** Texture is repeating outside of 0..1 UVs */
  17543. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17544. /** Texture is repeating and mirrored */
  17545. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17546. /** ALPHA */
  17547. Engine.TEXTUREFORMAT_ALPHA = 0;
  17548. /** LUMINANCE */
  17549. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17550. /** LUMINANCE_ALPHA */
  17551. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17552. /** RGB */
  17553. Engine.TEXTUREFORMAT_RGB = 4;
  17554. /** RGBA */
  17555. Engine.TEXTUREFORMAT_RGBA = 5;
  17556. /** RED */
  17557. Engine.TEXTUREFORMAT_RED = 6;
  17558. /** RED (2nd reference) */
  17559. Engine.TEXTUREFORMAT_R = 6;
  17560. /** RG */
  17561. Engine.TEXTUREFORMAT_RG = 7;
  17562. /** RED_INTEGER */
  17563. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17564. /** RED_INTEGER (2nd reference) */
  17565. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17566. /** RG_INTEGER */
  17567. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17568. /** RGB_INTEGER */
  17569. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17570. /** RGBA_INTEGER */
  17571. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17572. /** UNSIGNED_BYTE */
  17573. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17574. /** UNSIGNED_BYTE (2nd reference) */
  17575. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17576. /** FLOAT */
  17577. Engine.TEXTURETYPE_FLOAT = 1;
  17578. /** HALF_FLOAT */
  17579. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17580. /** BYTE */
  17581. Engine.TEXTURETYPE_BYTE = 3;
  17582. /** SHORT */
  17583. Engine.TEXTURETYPE_SHORT = 4;
  17584. /** UNSIGNED_SHORT */
  17585. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17586. /** INT */
  17587. Engine.TEXTURETYPE_INT = 6;
  17588. /** UNSIGNED_INT */
  17589. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17590. /** UNSIGNED_SHORT_4_4_4_4 */
  17591. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17592. /** UNSIGNED_SHORT_5_5_5_1 */
  17593. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17594. /** UNSIGNED_SHORT_5_6_5 */
  17595. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17596. /** UNSIGNED_INT_2_10_10_10_REV */
  17597. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17598. /** UNSIGNED_INT_24_8 */
  17599. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17600. /** UNSIGNED_INT_10F_11F_11F_REV */
  17601. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17602. /** UNSIGNED_INT_5_9_9_9_REV */
  17603. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17604. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17605. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17606. /** nearest is mag = nearest and min = nearest and mip = linear */
  17607. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17608. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17609. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17610. /** Trilinear is mag = linear and min = linear and mip = linear */
  17611. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17612. /** nearest is mag = nearest and min = nearest and mip = linear */
  17613. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17614. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17615. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17616. /** Trilinear is mag = linear and min = linear and mip = linear */
  17617. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17618. /** mag = nearest and min = nearest and mip = nearest */
  17619. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17620. /** mag = nearest and min = linear and mip = nearest */
  17621. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17622. /** mag = nearest and min = linear and mip = linear */
  17623. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17624. /** mag = nearest and min = linear and mip = none */
  17625. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17626. /** mag = nearest and min = nearest and mip = none */
  17627. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17628. /** mag = linear and min = nearest and mip = nearest */
  17629. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17630. /** mag = linear and min = nearest and mip = linear */
  17631. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17632. /** mag = linear and min = linear and mip = none */
  17633. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17634. /** mag = linear and min = nearest and mip = none */
  17635. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17636. /** Explicit coordinates mode */
  17637. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17638. /** Spherical coordinates mode */
  17639. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17640. /** Planar coordinates mode */
  17641. Engine.TEXTURE_PLANAR_MODE = 2;
  17642. /** Cubic coordinates mode */
  17643. Engine.TEXTURE_CUBIC_MODE = 3;
  17644. /** Projection coordinates mode */
  17645. Engine.TEXTURE_PROJECTION_MODE = 4;
  17646. /** Skybox coordinates mode */
  17647. Engine.TEXTURE_SKYBOX_MODE = 5;
  17648. /** Inverse Cubic coordinates mode */
  17649. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17650. /** Equirectangular coordinates mode */
  17651. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17652. /** Equirectangular Fixed coordinates mode */
  17653. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17654. /** Equirectangular Fixed Mirrored coordinates mode */
  17655. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17656. // Texture rescaling mode
  17657. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17658. Engine.SCALEMODE_FLOOR = 1;
  17659. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17660. Engine.SCALEMODE_NEAREST = 2;
  17661. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17662. Engine.SCALEMODE_CEILING = 3;
  17663. // Updatable statics so stick with vars here
  17664. /**
  17665. * Gets or sets the epsilon value used by collision engine
  17666. */
  17667. Engine.CollisionsEpsilon = 0.001;
  17668. /**
  17669. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17670. */
  17671. Engine.CodeRepository = "src/";
  17672. /**
  17673. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17674. */
  17675. Engine.ShadersRepository = "src/Shaders/";
  17676. return Engine;
  17677. }());
  17678. BABYLON.Engine = Engine;
  17679. })(BABYLON || (BABYLON = {}));
  17680. //# sourceMappingURL=babylon.engine.js.map
  17681. var BABYLON;
  17682. (function (BABYLON) {
  17683. /**
  17684. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17685. */
  17686. var Node = /** @class */ (function () {
  17687. /**
  17688. * Creates a new Node
  17689. * @param {string} name - the name and id to be given to this node
  17690. * @param {BABYLON.Scene} the scene this node will be added to
  17691. */
  17692. function Node(name, scene) {
  17693. if (scene === void 0) { scene = null; }
  17694. /**
  17695. * Gets or sets a string used to store user defined state for the node
  17696. */
  17697. this.state = "";
  17698. /**
  17699. * Gets or sets an object used to store user defined information for the node
  17700. */
  17701. this.metadata = null;
  17702. /**
  17703. * Gets or sets a boolean used to define if the node must be serialized
  17704. */
  17705. this.doNotSerialize = false;
  17706. /** @hidden */
  17707. this._isDisposed = false;
  17708. /**
  17709. * Gets a list of Animations associated with the node
  17710. */
  17711. this.animations = new Array();
  17712. this._ranges = {};
  17713. this._isEnabled = true;
  17714. this._isParentEnabled = true;
  17715. this._isReady = true;
  17716. /** @hidden */
  17717. this._currentRenderId = -1;
  17718. this._parentRenderId = -1;
  17719. this._childRenderId = -1;
  17720. /** @hidden */
  17721. this._worldMatrix = BABYLON.Matrix.Identity();
  17722. /** @hidden */
  17723. this._worldMatrixDeterminant = 0;
  17724. this._animationPropertiesOverride = null;
  17725. /**
  17726. * An event triggered when the mesh is disposed
  17727. */
  17728. this.onDisposeObservable = new BABYLON.Observable();
  17729. // Behaviors
  17730. this._behaviors = new Array();
  17731. this.name = name;
  17732. this.id = name;
  17733. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17734. this.uniqueId = this._scene.getUniqueId();
  17735. this._initCache();
  17736. this._scene.rootNodes.push(this);
  17737. }
  17738. /**
  17739. * Add a new node constructor
  17740. * @param type defines the type name of the node to construct
  17741. * @param constructorFunc defines the constructor function
  17742. */
  17743. Node.AddNodeConstructor = function (type, constructorFunc) {
  17744. this._NodeConstructors[type] = constructorFunc;
  17745. };
  17746. /**
  17747. * Returns a node constructor based on type name
  17748. * @param type defines the type name
  17749. * @param name defines the new node name
  17750. * @param scene defines the hosting scene
  17751. * @param options defines optional options to transmit to constructors
  17752. * @returns the new constructor or null
  17753. */
  17754. Node.Construct = function (type, name, scene, options) {
  17755. var constructorFunc = this._NodeConstructors[type];
  17756. if (!constructorFunc) {
  17757. return null;
  17758. }
  17759. return constructorFunc(name, scene, options);
  17760. };
  17761. /**
  17762. * Gets a boolean indicating if the node has been disposed
  17763. * @returns true if the node was disposed
  17764. */
  17765. Node.prototype.isDisposed = function () {
  17766. return this._isDisposed;
  17767. };
  17768. Object.defineProperty(Node.prototype, "parent", {
  17769. get: function () {
  17770. return this._parentNode;
  17771. },
  17772. /**
  17773. * Gets or sets the parent of the node
  17774. */
  17775. set: function (parent) {
  17776. if (this._parentNode === parent) {
  17777. return;
  17778. }
  17779. var previousParentNode = this._parentNode;
  17780. // Remove self from list of children of parent
  17781. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17782. var index = this._parentNode._children.indexOf(this);
  17783. if (index !== -1) {
  17784. this._parentNode._children.splice(index, 1);
  17785. }
  17786. if (!parent) {
  17787. // Need to add this node to the rootNodes
  17788. this._scene.rootNodes.push(this);
  17789. }
  17790. }
  17791. // Store new parent
  17792. this._parentNode = parent;
  17793. // Add as child to new parent
  17794. if (this._parentNode) {
  17795. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17796. this._parentNode._children = new Array();
  17797. }
  17798. this._parentNode._children.push(this);
  17799. if (!previousParentNode) {
  17800. // Need to remove from rootNodes
  17801. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17802. if (rootNodeIndex > -1) {
  17803. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17804. }
  17805. }
  17806. }
  17807. // Enabled state
  17808. this._syncParentEnabledState();
  17809. },
  17810. enumerable: true,
  17811. configurable: true
  17812. });
  17813. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17814. /**
  17815. * Gets or sets the animation properties override
  17816. */
  17817. get: function () {
  17818. if (!this._animationPropertiesOverride) {
  17819. return this._scene.animationPropertiesOverride;
  17820. }
  17821. return this._animationPropertiesOverride;
  17822. },
  17823. set: function (value) {
  17824. this._animationPropertiesOverride = value;
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. /**
  17830. * Gets a string idenfifying the name of the class
  17831. * @returns "Node" string
  17832. */
  17833. Node.prototype.getClassName = function () {
  17834. return "Node";
  17835. };
  17836. Object.defineProperty(Node.prototype, "onDispose", {
  17837. /**
  17838. * Sets a callback that will be raised when the node will be disposed
  17839. */
  17840. set: function (callback) {
  17841. if (this._onDisposeObserver) {
  17842. this.onDisposeObservable.remove(this._onDisposeObserver);
  17843. }
  17844. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. /**
  17850. * Gets the scene of the node
  17851. * @returns a {BABYLON.Scene}
  17852. */
  17853. Node.prototype.getScene = function () {
  17854. return this._scene;
  17855. };
  17856. /**
  17857. * Gets the engine of the node
  17858. * @returns a {BABYLON.Engine}
  17859. */
  17860. Node.prototype.getEngine = function () {
  17861. return this._scene.getEngine();
  17862. };
  17863. /**
  17864. * Attach a behavior to the node
  17865. * @see http://doc.babylonjs.com/features/behaviour
  17866. * @param behavior defines the behavior to attach
  17867. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  17868. * @returns the current Node
  17869. */
  17870. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  17871. var _this = this;
  17872. if (attachImmediately === void 0) { attachImmediately = false; }
  17873. var index = this._behaviors.indexOf(behavior);
  17874. if (index !== -1) {
  17875. return this;
  17876. }
  17877. behavior.init();
  17878. if (this._scene.isLoading && !attachImmediately) {
  17879. // We defer the attach when the scene will be loaded
  17880. this._scene.onDataLoadedObservable.addOnce(function () {
  17881. behavior.attach(_this);
  17882. });
  17883. }
  17884. else {
  17885. behavior.attach(this);
  17886. }
  17887. this._behaviors.push(behavior);
  17888. return this;
  17889. };
  17890. /**
  17891. * Remove an attached behavior
  17892. * @see http://doc.babylonjs.com/features/behaviour
  17893. * @param behavior defines the behavior to attach
  17894. * @returns the current Node
  17895. */
  17896. Node.prototype.removeBehavior = function (behavior) {
  17897. var index = this._behaviors.indexOf(behavior);
  17898. if (index === -1) {
  17899. return this;
  17900. }
  17901. this._behaviors[index].detach();
  17902. this._behaviors.splice(index, 1);
  17903. return this;
  17904. };
  17905. Object.defineProperty(Node.prototype, "behaviors", {
  17906. /**
  17907. * Gets the list of attached behaviors
  17908. * @see http://doc.babylonjs.com/features/behaviour
  17909. */
  17910. get: function () {
  17911. return this._behaviors;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. /**
  17917. * Gets an attached behavior by name
  17918. * @param name defines the name of the behavior to look for
  17919. * @see http://doc.babylonjs.com/features/behaviour
  17920. * @returns null if behavior was not found else the requested behavior
  17921. */
  17922. Node.prototype.getBehaviorByName = function (name) {
  17923. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17924. var behavior = _a[_i];
  17925. if (behavior.name === name) {
  17926. return behavior;
  17927. }
  17928. }
  17929. return null;
  17930. };
  17931. /**
  17932. * Returns the latest update of the World matrix
  17933. * @returns a Matrix
  17934. */
  17935. Node.prototype.getWorldMatrix = function () {
  17936. if (this._currentRenderId !== this._scene.getRenderId()) {
  17937. this.computeWorldMatrix();
  17938. }
  17939. return this._worldMatrix;
  17940. };
  17941. /** @hidden */
  17942. Node.prototype._getWorldMatrixDeterminant = function () {
  17943. return this._worldMatrixDeterminant;
  17944. };
  17945. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17946. /**
  17947. * Returns directly the latest state of the mesh World matrix.
  17948. * A Matrix is returned.
  17949. */
  17950. get: function () {
  17951. return this._worldMatrix;
  17952. },
  17953. enumerable: true,
  17954. configurable: true
  17955. });
  17956. // override it in derived class if you add new variables to the cache
  17957. // and call the parent class method
  17958. /** @hidden */
  17959. Node.prototype._initCache = function () {
  17960. this._cache = {};
  17961. this._cache.parent = undefined;
  17962. };
  17963. /** @hidden */
  17964. Node.prototype.updateCache = function (force) {
  17965. if (!force && this.isSynchronized())
  17966. return;
  17967. this._cache.parent = this.parent;
  17968. this._updateCache();
  17969. };
  17970. // override it in derived class if you add new variables to the cache
  17971. // and call the parent class method if !ignoreParentClass
  17972. /** @hidden */
  17973. Node.prototype._updateCache = function (ignoreParentClass) {
  17974. };
  17975. // override it in derived class if you add new variables to the cache
  17976. /** @hidden */
  17977. Node.prototype._isSynchronized = function () {
  17978. return true;
  17979. };
  17980. /** @hidden */
  17981. Node.prototype._markSyncedWithParent = function () {
  17982. if (this._parentNode) {
  17983. this._parentRenderId = this._parentNode._childRenderId;
  17984. }
  17985. };
  17986. /** @hidden */
  17987. Node.prototype.isSynchronizedWithParent = function () {
  17988. if (!this._parentNode) {
  17989. return true;
  17990. }
  17991. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17992. return false;
  17993. }
  17994. return this._parentNode.isSynchronized();
  17995. };
  17996. /** @hidden */
  17997. Node.prototype.isSynchronized = function () {
  17998. if (this._cache.parent != this._parentNode) {
  17999. this._cache.parent = this._parentNode;
  18000. return false;
  18001. }
  18002. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18003. return false;
  18004. }
  18005. return this._isSynchronized();
  18006. };
  18007. /**
  18008. * Is this node ready to be used/rendered
  18009. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18010. * @return true if the node is ready
  18011. */
  18012. Node.prototype.isReady = function (completeCheck) {
  18013. if (completeCheck === void 0) { completeCheck = false; }
  18014. return this._isReady;
  18015. };
  18016. /**
  18017. * Is this node enabled?
  18018. * 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
  18019. * @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
  18020. * @return whether this node (and its parent) is enabled
  18021. */
  18022. Node.prototype.isEnabled = function (checkAncestors) {
  18023. if (checkAncestors === void 0) { checkAncestors = true; }
  18024. if (checkAncestors === false) {
  18025. return this._isEnabled;
  18026. }
  18027. if (!this._isEnabled) {
  18028. return false;
  18029. }
  18030. return this._isParentEnabled;
  18031. };
  18032. /** @hidden */
  18033. Node.prototype._syncParentEnabledState = function () {
  18034. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18035. if (this._children) {
  18036. this._children.forEach(function (c) {
  18037. c._syncParentEnabledState(); // Force children to update accordingly
  18038. });
  18039. }
  18040. };
  18041. /**
  18042. * Set the enabled state of this node
  18043. * @param value defines the new enabled state
  18044. */
  18045. Node.prototype.setEnabled = function (value) {
  18046. this._isEnabled = value;
  18047. this._syncParentEnabledState();
  18048. };
  18049. /**
  18050. * Is this node a descendant of the given node?
  18051. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18052. * @param ancestor defines the parent node to inspect
  18053. * @returns a boolean indicating if this node is a descendant of the given node
  18054. */
  18055. Node.prototype.isDescendantOf = function (ancestor) {
  18056. if (this.parent) {
  18057. if (this.parent === ancestor) {
  18058. return true;
  18059. }
  18060. return this.parent.isDescendantOf(ancestor);
  18061. }
  18062. return false;
  18063. };
  18064. /** @hidden */
  18065. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18066. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18067. if (!this._children) {
  18068. return;
  18069. }
  18070. for (var index = 0; index < this._children.length; index++) {
  18071. var item = this._children[index];
  18072. if (!predicate || predicate(item)) {
  18073. results.push(item);
  18074. }
  18075. if (!directDescendantsOnly) {
  18076. item._getDescendants(results, false, predicate);
  18077. }
  18078. }
  18079. };
  18080. /**
  18081. * Will return all nodes that have this node as ascendant
  18082. * @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
  18083. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18084. * @return all children nodes of all types
  18085. */
  18086. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18087. var results = new Array();
  18088. this._getDescendants(results, directDescendantsOnly, predicate);
  18089. return results;
  18090. };
  18091. /**
  18092. * Get all child-meshes of this node
  18093. * @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
  18094. * @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
  18095. * @returns an array of {BABYLON.AbstractMesh}
  18096. */
  18097. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18098. var results = [];
  18099. this._getDescendants(results, directDescendantsOnly, function (node) {
  18100. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18101. });
  18102. return results;
  18103. };
  18104. /**
  18105. * Get all child-transformNodes of this node
  18106. * @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
  18107. * @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
  18108. * @returns an array of {BABYLON.TransformNode}
  18109. */
  18110. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18111. var results = [];
  18112. this._getDescendants(results, directDescendantsOnly, function (node) {
  18113. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18114. });
  18115. return results;
  18116. };
  18117. /**
  18118. * Get all direct children of this node
  18119. * @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
  18120. * @returns an array of {BABYLON.Node}
  18121. */
  18122. Node.prototype.getChildren = function (predicate) {
  18123. return this.getDescendants(true, predicate);
  18124. };
  18125. /** @hidden */
  18126. Node.prototype._setReady = function (state) {
  18127. if (state === this._isReady) {
  18128. return;
  18129. }
  18130. if (!state) {
  18131. this._isReady = false;
  18132. return;
  18133. }
  18134. if (this.onReady) {
  18135. this.onReady(this);
  18136. }
  18137. this._isReady = true;
  18138. };
  18139. /**
  18140. * Get an animation by name
  18141. * @param name defines the name of the animation to look for
  18142. * @returns null if not found else the requested animation
  18143. */
  18144. Node.prototype.getAnimationByName = function (name) {
  18145. for (var i = 0; i < this.animations.length; i++) {
  18146. var animation = this.animations[i];
  18147. if (animation.name === name) {
  18148. return animation;
  18149. }
  18150. }
  18151. return null;
  18152. };
  18153. /**
  18154. * Creates an animation range for this node
  18155. * @param name defines the name of the range
  18156. * @param from defines the starting key
  18157. * @param to defines the end key
  18158. */
  18159. Node.prototype.createAnimationRange = function (name, from, to) {
  18160. // check name not already in use
  18161. if (!this._ranges[name]) {
  18162. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18163. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18164. if (this.animations[i]) {
  18165. this.animations[i].createRange(name, from, to);
  18166. }
  18167. }
  18168. }
  18169. };
  18170. /**
  18171. * Delete a specific animation range
  18172. * @param name defines the name of the range to delete
  18173. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18174. */
  18175. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18176. if (deleteFrames === void 0) { deleteFrames = true; }
  18177. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18178. if (this.animations[i]) {
  18179. this.animations[i].deleteRange(name, deleteFrames);
  18180. }
  18181. }
  18182. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18183. };
  18184. /**
  18185. * Get an animation range by name
  18186. * @param name defines the name of the animation range to look for
  18187. * @returns null if not found else the requested animation range
  18188. */
  18189. Node.prototype.getAnimationRange = function (name) {
  18190. return this._ranges[name];
  18191. };
  18192. /**
  18193. * Will start the animation sequence
  18194. * @param name defines the range frames for animation sequence
  18195. * @param loop defines if the animation should loop (false by default)
  18196. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18197. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18198. * @returns the object created for this animation. If range does not exist, it will return null
  18199. */
  18200. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18201. var range = this.getAnimationRange(name);
  18202. if (!range) {
  18203. return null;
  18204. }
  18205. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18206. };
  18207. /**
  18208. * Serialize animation ranges into a JSON compatible object
  18209. * @returns serialization object
  18210. */
  18211. Node.prototype.serializeAnimationRanges = function () {
  18212. var serializationRanges = [];
  18213. for (var name in this._ranges) {
  18214. var localRange = this._ranges[name];
  18215. if (!localRange) {
  18216. continue;
  18217. }
  18218. var range = {};
  18219. range.name = name;
  18220. range.from = localRange.from;
  18221. range.to = localRange.to;
  18222. serializationRanges.push(range);
  18223. }
  18224. return serializationRanges;
  18225. };
  18226. /**
  18227. * Computes the world matrix of the node
  18228. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18229. * @returns the world matrix
  18230. */
  18231. Node.prototype.computeWorldMatrix = function (force) {
  18232. if (!this._worldMatrix) {
  18233. this._worldMatrix = BABYLON.Matrix.Identity();
  18234. }
  18235. return this._worldMatrix;
  18236. };
  18237. /**
  18238. * Releases resources associated with this node.
  18239. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18240. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18241. */
  18242. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18243. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18244. if (!doNotRecurse) {
  18245. var nodes = this.getDescendants(true);
  18246. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18247. var node = nodes_1[_i];
  18248. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18249. }
  18250. }
  18251. else {
  18252. var transformNodes = this.getChildTransformNodes(true);
  18253. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18254. var transformNode = transformNodes_1[_a];
  18255. transformNode.parent = null;
  18256. transformNode.computeWorldMatrix(true);
  18257. }
  18258. }
  18259. if (!this.parent) {
  18260. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18261. if (rootNodeIndex > -1) {
  18262. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18263. }
  18264. }
  18265. else {
  18266. this.parent = null;
  18267. }
  18268. // Callback
  18269. this.onDisposeObservable.notifyObservers(this);
  18270. this.onDisposeObservable.clear();
  18271. // Behaviors
  18272. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18273. var behavior = _c[_b];
  18274. behavior.detach();
  18275. }
  18276. this._behaviors = [];
  18277. this._isDisposed = true;
  18278. };
  18279. /**
  18280. * Parse animation range data from a serialization object and store them into a given node
  18281. * @param node defines where to store the animation ranges
  18282. * @param parsedNode defines the serialization object to read data from
  18283. * @param scene defines the hosting scene
  18284. */
  18285. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18286. if (parsedNode.ranges) {
  18287. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18288. var data = parsedNode.ranges[index];
  18289. node.createAnimationRange(data.name, data.from, data.to);
  18290. }
  18291. }
  18292. };
  18293. Node._NodeConstructors = {};
  18294. __decorate([
  18295. BABYLON.serialize()
  18296. ], Node.prototype, "name", void 0);
  18297. __decorate([
  18298. BABYLON.serialize()
  18299. ], Node.prototype, "id", void 0);
  18300. __decorate([
  18301. BABYLON.serialize()
  18302. ], Node.prototype, "uniqueId", void 0);
  18303. __decorate([
  18304. BABYLON.serialize()
  18305. ], Node.prototype, "state", void 0);
  18306. __decorate([
  18307. BABYLON.serialize()
  18308. ], Node.prototype, "metadata", void 0);
  18309. return Node;
  18310. }());
  18311. BABYLON.Node = Node;
  18312. })(BABYLON || (BABYLON = {}));
  18313. //# sourceMappingURL=babylon.node.js.map
  18314. var BABYLON;
  18315. (function (BABYLON) {
  18316. // This matrix is used as a value to reset the bounding box.
  18317. var _identityMatrix = BABYLON.Matrix.Identity();
  18318. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18319. var BoundingSphere = /** @class */ (function () {
  18320. /**
  18321. * Creates a new bounding sphere
  18322. * @param min defines the minimum vector (in local space)
  18323. * @param max defines the maximum vector (in local space)
  18324. */
  18325. function BoundingSphere(min, max) {
  18326. this.center = BABYLON.Vector3.Zero();
  18327. this.centerWorld = BABYLON.Vector3.Zero();
  18328. this.reConstruct(min, max);
  18329. }
  18330. /**
  18331. * Recreates the entire bounding sphere from scratch
  18332. * @param min defines the new minimum vector (in local space)
  18333. * @param max defines the new maximum vector (in local space)
  18334. */
  18335. BoundingSphere.prototype.reConstruct = function (min, max) {
  18336. this.minimum = min.clone();
  18337. this.maximum = max.clone();
  18338. var distance = BABYLON.Vector3.Distance(min, max);
  18339. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18340. this.radius = distance * 0.5;
  18341. this.centerWorld.set(0, 0, 0);
  18342. this._update(_identityMatrix);
  18343. };
  18344. /**
  18345. * Scale the current bounding sphere by applying a scale factor
  18346. * @param factor defines the scale factor to apply
  18347. * @returns the current bounding box
  18348. */
  18349. BoundingSphere.prototype.scale = function (factor) {
  18350. var newRadius = this.radius * factor;
  18351. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18352. var min = this.center.subtract(_tempRadiusVector);
  18353. var max = this.center.add(_tempRadiusVector);
  18354. this.reConstruct(min, max);
  18355. return this;
  18356. };
  18357. // Methods
  18358. /** @hidden */
  18359. BoundingSphere.prototype._update = function (world) {
  18360. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18361. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18362. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18363. };
  18364. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18365. for (var i = 0; i < 6; i++) {
  18366. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18367. return false;
  18368. }
  18369. return true;
  18370. };
  18371. BoundingSphere.prototype.intersectsPoint = function (point) {
  18372. var x = this.centerWorld.x - point.x;
  18373. var y = this.centerWorld.y - point.y;
  18374. var z = this.centerWorld.z - point.z;
  18375. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18376. if (this.radiusWorld < distance)
  18377. return false;
  18378. return true;
  18379. };
  18380. // Statics
  18381. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18382. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18383. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18384. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18385. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18386. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18387. return false;
  18388. return true;
  18389. };
  18390. return BoundingSphere;
  18391. }());
  18392. BABYLON.BoundingSphere = BoundingSphere;
  18393. })(BABYLON || (BABYLON = {}));
  18394. //# sourceMappingURL=babylon.boundingSphere.js.map
  18395. var BABYLON;
  18396. (function (BABYLON) {
  18397. /**
  18398. * Class used to store bounding box information
  18399. */
  18400. var BoundingBox = /** @class */ (function () {
  18401. /**
  18402. * Creates a new bounding box
  18403. * @param min defines the minimum vector (in local space)
  18404. * @param max defines the maximum vector (in local space)
  18405. */
  18406. function BoundingBox(min, max) {
  18407. /**
  18408. * Gets the 8 vectors representing the bounding box in world space
  18409. */
  18410. this.vectorsWorld = new Array();
  18411. this.reConstruct(min, max);
  18412. }
  18413. // Methods
  18414. /**
  18415. * Recreates the entire bounding box from scratch
  18416. * @param min defines the new minimum vector (in local space)
  18417. * @param max defines the new maximum vector (in local space)
  18418. */
  18419. BoundingBox.prototype.reConstruct = function (min, max) {
  18420. this.minimum = min.clone();
  18421. this.maximum = max.clone();
  18422. // Bounding vectors
  18423. this.vectors = [
  18424. this.minimum.clone(),
  18425. this.maximum.clone(),
  18426. this.minimum.clone(),
  18427. this.minimum.clone(),
  18428. this.minimum.clone(),
  18429. this.maximum.clone(),
  18430. this.maximum.clone(),
  18431. this.maximum.clone()
  18432. ];
  18433. this.vectors[2].x = this.maximum.x;
  18434. this.vectors[3].y = this.maximum.y;
  18435. this.vectors[4].z = this.maximum.z;
  18436. this.vectors[5].z = this.minimum.z;
  18437. this.vectors[6].x = this.minimum.x;
  18438. this.vectors[7].y = this.minimum.y;
  18439. // OBB
  18440. this.center = this.maximum.add(this.minimum).scale(0.5);
  18441. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18442. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18443. // World
  18444. for (var index = 0; index < this.vectors.length; index++) {
  18445. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18446. }
  18447. this.minimumWorld = BABYLON.Vector3.Zero();
  18448. this.maximumWorld = BABYLON.Vector3.Zero();
  18449. this.centerWorld = BABYLON.Vector3.Zero();
  18450. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18451. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18452. };
  18453. /**
  18454. * Scale the current bounding box by applying a scale factor
  18455. * @param factor defines the scale factor to apply
  18456. * @returns the current bounding box
  18457. */
  18458. BoundingBox.prototype.scale = function (factor) {
  18459. var diff = this.maximum.subtract(this.minimum);
  18460. var distance = diff.length() * factor;
  18461. diff.normalize();
  18462. var newRadius = diff.scale(distance / 2);
  18463. var min = this.center.subtract(newRadius);
  18464. var max = this.center.add(newRadius);
  18465. this.reConstruct(min, max);
  18466. return this;
  18467. };
  18468. /**
  18469. * Gets the world matrix of the bounding box
  18470. * @returns a matrix
  18471. */
  18472. BoundingBox.prototype.getWorldMatrix = function () {
  18473. return this._worldMatrix;
  18474. };
  18475. /**
  18476. * Sets the world matrix stored in the bounding box
  18477. * @param matrix defines the matrix to store
  18478. * @returns current bounding box
  18479. */
  18480. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18481. this._worldMatrix.copyFrom(matrix);
  18482. return this;
  18483. };
  18484. /** @hidden */
  18485. BoundingBox.prototype._update = function (world) {
  18486. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18487. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18488. for (var index = 0; index < this.vectors.length; index++) {
  18489. var v = this.vectorsWorld[index];
  18490. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18491. if (v.x < this.minimumWorld.x)
  18492. this.minimumWorld.x = v.x;
  18493. if (v.y < this.minimumWorld.y)
  18494. this.minimumWorld.y = v.y;
  18495. if (v.z < this.minimumWorld.z)
  18496. this.minimumWorld.z = v.z;
  18497. if (v.x > this.maximumWorld.x)
  18498. this.maximumWorld.x = v.x;
  18499. if (v.y > this.maximumWorld.y)
  18500. this.maximumWorld.y = v.y;
  18501. if (v.z > this.maximumWorld.z)
  18502. this.maximumWorld.z = v.z;
  18503. }
  18504. // Extend
  18505. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18506. this.extendSizeWorld.scaleInPlace(0.5);
  18507. // OBB
  18508. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18509. this.centerWorld.scaleInPlace(0.5);
  18510. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18511. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18512. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18513. this._worldMatrix = world;
  18514. };
  18515. /**
  18516. * Tests if the bounding box is intersecting the frustum planes
  18517. * @param frustumPlanes defines the frustum planes to test
  18518. * @returns true if there is an intersection
  18519. */
  18520. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18521. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18522. };
  18523. /**
  18524. * Tests if the bounding box is entirely inside the frustum planes
  18525. * @param frustumPlanes defines the frustum planes to test
  18526. * @returns true if there is an inclusion
  18527. */
  18528. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18529. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18530. };
  18531. /**
  18532. * Tests if a point is inside the bounding box
  18533. * @param point defines the point to test
  18534. * @returns true if the point is inside the bounding box
  18535. */
  18536. BoundingBox.prototype.intersectsPoint = function (point) {
  18537. var delta = -BABYLON.Epsilon;
  18538. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18539. return false;
  18540. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18541. return false;
  18542. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18543. return false;
  18544. return true;
  18545. };
  18546. /**
  18547. * Tests if the bounding box intersects with a bounding sphere
  18548. * @param sphere defines the sphere to test
  18549. * @returns true if there is an intersection
  18550. */
  18551. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18552. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18553. };
  18554. /**
  18555. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18556. * @param min defines the min vector to use
  18557. * @param max defines the max vector to use
  18558. * @returns true if there is an intersection
  18559. */
  18560. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18561. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18562. return false;
  18563. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18564. return false;
  18565. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18566. return false;
  18567. return true;
  18568. };
  18569. // Statics
  18570. /**
  18571. * Tests if two bounding boxes are intersections
  18572. * @param box0 defines the first box to test
  18573. * @param box1 defines the second box to test
  18574. * @returns true if there is an intersection
  18575. */
  18576. BoundingBox.Intersects = function (box0, box1) {
  18577. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18578. return false;
  18579. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18580. return false;
  18581. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18582. return false;
  18583. return true;
  18584. };
  18585. /**
  18586. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18587. * @param minPoint defines the minimum vector of the bounding box
  18588. * @param maxPoint defines the maximum vector of the bounding box
  18589. * @param sphereCenter defines the sphere center
  18590. * @param sphereRadius defines the sphere radius
  18591. * @returns true if there is an intersection
  18592. */
  18593. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18594. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18595. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18596. return (num <= (sphereRadius * sphereRadius));
  18597. };
  18598. /**
  18599. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18600. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18601. * @param frustumPlanes defines the frustum planes to test
  18602. * @return true if there is an inclusion
  18603. */
  18604. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18605. for (var p = 0; p < 6; p++) {
  18606. for (var i = 0; i < 8; i++) {
  18607. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18608. return false;
  18609. }
  18610. }
  18611. }
  18612. return true;
  18613. };
  18614. /**
  18615. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18616. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18617. * @param frustumPlanes defines the frustum planes to test
  18618. * @return true if there is an intersection
  18619. */
  18620. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18621. for (var p = 0; p < 6; p++) {
  18622. var inCount = 8;
  18623. for (var i = 0; i < 8; i++) {
  18624. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18625. --inCount;
  18626. }
  18627. else {
  18628. break;
  18629. }
  18630. }
  18631. if (inCount === 0)
  18632. return false;
  18633. }
  18634. return true;
  18635. };
  18636. return BoundingBox;
  18637. }());
  18638. BABYLON.BoundingBox = BoundingBox;
  18639. })(BABYLON || (BABYLON = {}));
  18640. //# sourceMappingURL=babylon.boundingBox.js.map
  18641. var BABYLON;
  18642. (function (BABYLON) {
  18643. var computeBoxExtents = function (axis, box) {
  18644. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18645. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18646. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18647. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18648. var r = r0 + r1 + r2;
  18649. return {
  18650. min: p - r,
  18651. max: p + r
  18652. };
  18653. };
  18654. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18655. var axisOverlap = function (axis, box0, box1) {
  18656. var result0 = computeBoxExtents(axis, box0);
  18657. var result1 = computeBoxExtents(axis, box1);
  18658. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18659. };
  18660. var BoundingInfo = /** @class */ (function () {
  18661. function BoundingInfo(minimum, maximum) {
  18662. this.minimum = minimum;
  18663. this.maximum = maximum;
  18664. this._isLocked = false;
  18665. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18666. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18667. }
  18668. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18669. get: function () {
  18670. return this._isLocked;
  18671. },
  18672. set: function (value) {
  18673. this._isLocked = value;
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. // Methods
  18679. BoundingInfo.prototype.update = function (world) {
  18680. if (this._isLocked) {
  18681. return;
  18682. }
  18683. this.boundingBox._update(world);
  18684. this.boundingSphere._update(world);
  18685. };
  18686. /**
  18687. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18688. * @param center New center of the bounding info
  18689. * @param extend New extend of the bounding info
  18690. */
  18691. BoundingInfo.prototype.centerOn = function (center, extend) {
  18692. this.minimum = center.subtract(extend);
  18693. this.maximum = center.add(extend);
  18694. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18695. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18696. return this;
  18697. };
  18698. /**
  18699. * Scale the current bounding info by applying a scale factor
  18700. * @param factor defines the scale factor to apply
  18701. * @returns the current bounding info
  18702. */
  18703. BoundingInfo.prototype.scale = function (factor) {
  18704. this.boundingBox.scale(factor);
  18705. this.boundingSphere.scale(factor);
  18706. return this;
  18707. };
  18708. /**
  18709. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18710. * @param frustumPlanes defines the frustum to test
  18711. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18712. * @returns true if the bounding info is in the frustum planes
  18713. */
  18714. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18715. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18716. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18717. return false;
  18718. }
  18719. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18720. return true;
  18721. }
  18722. return this.boundingBox.isInFrustum(frustumPlanes);
  18723. };
  18724. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18725. /**
  18726. * Gets the world distance between the min and max points of the bounding box
  18727. */
  18728. get: function () {
  18729. var boundingBox = this.boundingBox;
  18730. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18731. return size.length();
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18737. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18738. };
  18739. /** @hidden */
  18740. BoundingInfo.prototype._checkCollision = function (collider) {
  18741. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18742. };
  18743. BoundingInfo.prototype.intersectsPoint = function (point) {
  18744. if (!this.boundingSphere.centerWorld) {
  18745. return false;
  18746. }
  18747. if (!this.boundingSphere.intersectsPoint(point)) {
  18748. return false;
  18749. }
  18750. if (!this.boundingBox.intersectsPoint(point)) {
  18751. return false;
  18752. }
  18753. return true;
  18754. };
  18755. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18756. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18757. return false;
  18758. }
  18759. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18760. return false;
  18761. }
  18762. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18763. return false;
  18764. }
  18765. if (!precise) {
  18766. return true;
  18767. }
  18768. var box0 = this.boundingBox;
  18769. var box1 = boundingInfo.boundingBox;
  18770. if (!axisOverlap(box0.directions[0], box0, box1))
  18771. return false;
  18772. if (!axisOverlap(box0.directions[1], box0, box1))
  18773. return false;
  18774. if (!axisOverlap(box0.directions[2], box0, box1))
  18775. return false;
  18776. if (!axisOverlap(box1.directions[0], box0, box1))
  18777. return false;
  18778. if (!axisOverlap(box1.directions[1], box0, box1))
  18779. return false;
  18780. if (!axisOverlap(box1.directions[2], box0, box1))
  18781. return false;
  18782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18783. return false;
  18784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18785. return false;
  18786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18787. return false;
  18788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18789. return false;
  18790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18791. return false;
  18792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18793. return false;
  18794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18795. return false;
  18796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18797. return false;
  18798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18799. return false;
  18800. return true;
  18801. };
  18802. return BoundingInfo;
  18803. }());
  18804. BABYLON.BoundingInfo = BoundingInfo;
  18805. })(BABYLON || (BABYLON = {}));
  18806. //# sourceMappingURL=babylon.boundingInfo.js.map
  18807. var BABYLON;
  18808. (function (BABYLON) {
  18809. var TransformNode = /** @class */ (function (_super) {
  18810. __extends(TransformNode, _super);
  18811. function TransformNode(name, scene, isPure) {
  18812. if (scene === void 0) { scene = null; }
  18813. if (isPure === void 0) { isPure = true; }
  18814. var _this = _super.call(this, name, scene) || this;
  18815. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18816. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18817. _this._up = new BABYLON.Vector3(0, 1, 0);
  18818. _this._right = new BABYLON.Vector3(1, 0, 0);
  18819. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18820. // Properties
  18821. _this._position = BABYLON.Vector3.Zero();
  18822. _this._rotation = BABYLON.Vector3.Zero();
  18823. _this._scaling = BABYLON.Vector3.One();
  18824. _this._isDirty = false;
  18825. /**
  18826. * Set the billboard mode. Default is 0.
  18827. *
  18828. * | Value | Type | Description |
  18829. * | --- | --- | --- |
  18830. * | 0 | BILLBOARDMODE_NONE | |
  18831. * | 1 | BILLBOARDMODE_X | |
  18832. * | 2 | BILLBOARDMODE_Y | |
  18833. * | 4 | BILLBOARDMODE_Z | |
  18834. * | 7 | BILLBOARDMODE_ALL | |
  18835. *
  18836. */
  18837. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18838. _this.scalingDeterminant = 1;
  18839. _this.infiniteDistance = false;
  18840. /**
  18841. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18842. * By default the system will update normals to compensate
  18843. */
  18844. _this.ignoreNonUniformScaling = false;
  18845. _this._localWorld = BABYLON.Matrix.Zero();
  18846. _this._absolutePosition = BABYLON.Vector3.Zero();
  18847. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18848. _this._postMultiplyPivotMatrix = false;
  18849. _this._isWorldMatrixFrozen = false;
  18850. /**
  18851. * An event triggered after the world matrix is updated
  18852. */
  18853. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18854. _this._nonUniformScaling = false;
  18855. if (isPure) {
  18856. _this.getScene().addTransformNode(_this);
  18857. }
  18858. return _this;
  18859. }
  18860. /**
  18861. * Gets a string identifying the name of the class
  18862. * @returns "TransformNode" string
  18863. */
  18864. TransformNode.prototype.getClassName = function () {
  18865. return "TransformNode";
  18866. };
  18867. Object.defineProperty(TransformNode.prototype, "position", {
  18868. /**
  18869. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18870. */
  18871. get: function () {
  18872. return this._position;
  18873. },
  18874. set: function (newPosition) {
  18875. this._position = newPosition;
  18876. this._isDirty = true;
  18877. },
  18878. enumerable: true,
  18879. configurable: true
  18880. });
  18881. Object.defineProperty(TransformNode.prototype, "rotation", {
  18882. /**
  18883. * 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)).
  18884. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18885. */
  18886. get: function () {
  18887. return this._rotation;
  18888. },
  18889. set: function (newRotation) {
  18890. this._rotation = newRotation;
  18891. this._isDirty = true;
  18892. },
  18893. enumerable: true,
  18894. configurable: true
  18895. });
  18896. Object.defineProperty(TransformNode.prototype, "scaling", {
  18897. /**
  18898. * 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)).
  18899. */
  18900. get: function () {
  18901. return this._scaling;
  18902. },
  18903. set: function (newScaling) {
  18904. this._scaling = newScaling;
  18905. this._isDirty = true;
  18906. },
  18907. enumerable: true,
  18908. configurable: true
  18909. });
  18910. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18911. /**
  18912. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18913. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18914. */
  18915. get: function () {
  18916. return this._rotationQuaternion;
  18917. },
  18918. set: function (quaternion) {
  18919. this._rotationQuaternion = quaternion;
  18920. //reset the rotation vector.
  18921. if (quaternion && this.rotation.length()) {
  18922. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18923. }
  18924. },
  18925. enumerable: true,
  18926. configurable: true
  18927. });
  18928. Object.defineProperty(TransformNode.prototype, "forward", {
  18929. /**
  18930. * The forward direction of that transform in world space.
  18931. */
  18932. get: function () {
  18933. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18934. },
  18935. enumerable: true,
  18936. configurable: true
  18937. });
  18938. Object.defineProperty(TransformNode.prototype, "up", {
  18939. /**
  18940. * The up direction of that transform in world space.
  18941. */
  18942. get: function () {
  18943. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18944. },
  18945. enumerable: true,
  18946. configurable: true
  18947. });
  18948. Object.defineProperty(TransformNode.prototype, "right", {
  18949. /**
  18950. * The right direction of that transform in world space.
  18951. */
  18952. get: function () {
  18953. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18954. },
  18955. enumerable: true,
  18956. configurable: true
  18957. });
  18958. /**
  18959. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18960. * Returns the TransformNode.
  18961. */
  18962. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18963. this._poseMatrix.copyFrom(matrix);
  18964. return this;
  18965. };
  18966. /**
  18967. * Returns the mesh Pose matrix.
  18968. * Returned object : Matrix
  18969. */
  18970. TransformNode.prototype.getPoseMatrix = function () {
  18971. return this._poseMatrix;
  18972. };
  18973. /** @hidden */
  18974. TransformNode.prototype._isSynchronized = function () {
  18975. if (this._isDirty) {
  18976. return false;
  18977. }
  18978. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18979. return false;
  18980. if (this._cache.pivotMatrixUpdated) {
  18981. return false;
  18982. }
  18983. if (this.infiniteDistance) {
  18984. return false;
  18985. }
  18986. if (!this._cache.position.equals(this._position))
  18987. return false;
  18988. if (this._rotationQuaternion) {
  18989. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18990. return false;
  18991. }
  18992. if (!this._cache.rotation.equals(this._rotation))
  18993. return false;
  18994. if (!this._cache.scaling.equals(this._scaling))
  18995. return false;
  18996. return true;
  18997. };
  18998. /** @hidden */
  18999. TransformNode.prototype._initCache = function () {
  19000. _super.prototype._initCache.call(this);
  19001. this._cache.localMatrixUpdated = false;
  19002. this._cache.position = BABYLON.Vector3.Zero();
  19003. this._cache.scaling = BABYLON.Vector3.Zero();
  19004. this._cache.rotation = BABYLON.Vector3.Zero();
  19005. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19006. this._cache.billboardMode = -1;
  19007. };
  19008. TransformNode.prototype.markAsDirty = function (property) {
  19009. if (property === "rotation") {
  19010. this.rotationQuaternion = null;
  19011. }
  19012. this._currentRenderId = Number.MAX_VALUE;
  19013. this._isDirty = true;
  19014. return this;
  19015. };
  19016. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19017. /**
  19018. * Returns the current mesh absolute position.
  19019. * Returns a Vector3.
  19020. */
  19021. get: function () {
  19022. return this._absolutePosition;
  19023. },
  19024. enumerable: true,
  19025. configurable: true
  19026. });
  19027. /**
  19028. * Sets a new matrix to apply before all other transformation
  19029. * @param matrix defines the transform matrix
  19030. * @returns the current TransformNode
  19031. */
  19032. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19033. return this.setPivotMatrix(matrix, false);
  19034. };
  19035. /**
  19036. * Sets a new pivot matrix to the current node
  19037. * @param matrix defines the new pivot matrix to use
  19038. * @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
  19039. * @returns the current TransformNode
  19040. */
  19041. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19042. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19043. this._pivotMatrix = matrix.clone();
  19044. this._cache.pivotMatrixUpdated = true;
  19045. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19046. if (this._postMultiplyPivotMatrix) {
  19047. if (!this._pivotMatrixInverse) {
  19048. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19049. }
  19050. else {
  19051. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19052. }
  19053. }
  19054. return this;
  19055. };
  19056. /**
  19057. * Returns the mesh pivot matrix.
  19058. * Default : Identity.
  19059. * A Matrix is returned.
  19060. */
  19061. TransformNode.prototype.getPivotMatrix = function () {
  19062. return this._pivotMatrix;
  19063. };
  19064. /**
  19065. * Prevents the World matrix to be computed any longer.
  19066. * Returns the TransformNode.
  19067. */
  19068. TransformNode.prototype.freezeWorldMatrix = function () {
  19069. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19070. this.computeWorldMatrix(true);
  19071. this._isWorldMatrixFrozen = true;
  19072. return this;
  19073. };
  19074. /**
  19075. * Allows back the World matrix computation.
  19076. * Returns the TransformNode.
  19077. */
  19078. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19079. this._isWorldMatrixFrozen = false;
  19080. this.computeWorldMatrix(true);
  19081. return this;
  19082. };
  19083. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19084. /**
  19085. * True if the World matrix has been frozen.
  19086. * Returns a boolean.
  19087. */
  19088. get: function () {
  19089. return this._isWorldMatrixFrozen;
  19090. },
  19091. enumerable: true,
  19092. configurable: true
  19093. });
  19094. /**
  19095. * Retuns the mesh absolute position in the World.
  19096. * Returns a Vector3.
  19097. */
  19098. TransformNode.prototype.getAbsolutePosition = function () {
  19099. this.computeWorldMatrix();
  19100. return this._absolutePosition;
  19101. };
  19102. /**
  19103. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19104. * Returns the TransformNode.
  19105. */
  19106. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19107. if (!absolutePosition) {
  19108. return this;
  19109. }
  19110. var absolutePositionX;
  19111. var absolutePositionY;
  19112. var absolutePositionZ;
  19113. if (absolutePosition.x === undefined) {
  19114. if (arguments.length < 3) {
  19115. return this;
  19116. }
  19117. absolutePositionX = arguments[0];
  19118. absolutePositionY = arguments[1];
  19119. absolutePositionZ = arguments[2];
  19120. }
  19121. else {
  19122. absolutePositionX = absolutePosition.x;
  19123. absolutePositionY = absolutePosition.y;
  19124. absolutePositionZ = absolutePosition.z;
  19125. }
  19126. if (this.parent) {
  19127. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19128. invertParentWorldMatrix.invert();
  19129. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19130. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19131. }
  19132. else {
  19133. this.position.x = absolutePositionX;
  19134. this.position.y = absolutePositionY;
  19135. this.position.z = absolutePositionZ;
  19136. }
  19137. return this;
  19138. };
  19139. /**
  19140. * Sets the mesh position in its local space.
  19141. * Returns the TransformNode.
  19142. */
  19143. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19144. this.computeWorldMatrix();
  19145. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19146. return this;
  19147. };
  19148. /**
  19149. * Returns the mesh position in the local space from the current World matrix values.
  19150. * Returns a new Vector3.
  19151. */
  19152. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19153. this.computeWorldMatrix();
  19154. var invLocalWorldMatrix = this._localWorld.clone();
  19155. invLocalWorldMatrix.invert();
  19156. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19157. };
  19158. /**
  19159. * Translates the mesh along the passed Vector3 in its local space.
  19160. * Returns the TransformNode.
  19161. */
  19162. TransformNode.prototype.locallyTranslate = function (vector3) {
  19163. this.computeWorldMatrix(true);
  19164. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19165. return this;
  19166. };
  19167. /**
  19168. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19169. * @param targetPoint the position (must be in same space as current mesh) to look at
  19170. * @param yawCor optional yaw (y-axis) correction in radians
  19171. * @param pitchCor optional pitch (x-axis) correction in radians
  19172. * @param rollCor optional roll (z-axis) correction in radians
  19173. * @param space the choosen space of the target
  19174. * @returns the TransformNode.
  19175. */
  19176. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19177. if (yawCor === void 0) { yawCor = 0; }
  19178. if (pitchCor === void 0) { pitchCor = 0; }
  19179. if (rollCor === void 0) { rollCor = 0; }
  19180. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19181. var dv = TransformNode._lookAtVectorCache;
  19182. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19183. targetPoint.subtractToRef(pos, dv);
  19184. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19185. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19186. var pitch = Math.atan2(dv.y, len);
  19187. if (this.rotationQuaternion) {
  19188. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19189. }
  19190. else {
  19191. this.rotation.x = pitch + pitchCor;
  19192. this.rotation.y = yaw + yawCor;
  19193. this.rotation.z = rollCor;
  19194. }
  19195. return this;
  19196. };
  19197. /**
  19198. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19199. * This Vector3 is expressed in the World space.
  19200. */
  19201. TransformNode.prototype.getDirection = function (localAxis) {
  19202. var result = BABYLON.Vector3.Zero();
  19203. this.getDirectionToRef(localAxis, result);
  19204. return result;
  19205. };
  19206. /**
  19207. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19208. * localAxis is expressed in the mesh local space.
  19209. * result is computed in the Wordl space from the mesh World matrix.
  19210. * Returns the TransformNode.
  19211. */
  19212. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19213. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19214. return this;
  19215. };
  19216. /**
  19217. * Sets a new pivot point to the current node
  19218. * @param point defines the new pivot point to use
  19219. * @param space defines if the point is in world or local space (local by default)
  19220. * @returns the current TransformNode
  19221. */
  19222. TransformNode.prototype.setPivotPoint = function (point, space) {
  19223. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19224. if (this.getScene().getRenderId() == 0) {
  19225. this.computeWorldMatrix(true);
  19226. }
  19227. var wm = this.getWorldMatrix();
  19228. if (space == BABYLON.Space.WORLD) {
  19229. var tmat = BABYLON.Tmp.Matrix[0];
  19230. wm.invertToRef(tmat);
  19231. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19232. }
  19233. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19234. };
  19235. /**
  19236. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19237. */
  19238. TransformNode.prototype.getPivotPoint = function () {
  19239. var point = BABYLON.Vector3.Zero();
  19240. this.getPivotPointToRef(point);
  19241. return point;
  19242. };
  19243. /**
  19244. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19245. * Returns the TransformNode.
  19246. */
  19247. TransformNode.prototype.getPivotPointToRef = function (result) {
  19248. result.x = -this._pivotMatrix.m[12];
  19249. result.y = -this._pivotMatrix.m[13];
  19250. result.z = -this._pivotMatrix.m[14];
  19251. return this;
  19252. };
  19253. /**
  19254. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19255. */
  19256. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19257. var point = BABYLON.Vector3.Zero();
  19258. this.getAbsolutePivotPointToRef(point);
  19259. return point;
  19260. };
  19261. /**
  19262. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19263. * Returns the TransformNode.
  19264. */
  19265. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19266. result.x = this._pivotMatrix.m[12];
  19267. result.y = this._pivotMatrix.m[13];
  19268. result.z = this._pivotMatrix.m[14];
  19269. this.getPivotPointToRef(result);
  19270. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19271. return this;
  19272. };
  19273. /**
  19274. * Defines the passed node as the parent of the current node.
  19275. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19276. * Returns the TransformNode.
  19277. */
  19278. TransformNode.prototype.setParent = function (node) {
  19279. if (!node && !this.parent) {
  19280. return this;
  19281. }
  19282. if (!node) {
  19283. var rotation = BABYLON.Tmp.Quaternion[0];
  19284. var position = BABYLON.Tmp.Vector3[0];
  19285. var scale = BABYLON.Tmp.Vector3[1];
  19286. if (this.parent && this.parent.computeWorldMatrix) {
  19287. this.parent.computeWorldMatrix(true);
  19288. }
  19289. this.computeWorldMatrix(true);
  19290. this.getWorldMatrix().decompose(scale, rotation, position);
  19291. if (this.rotationQuaternion) {
  19292. this.rotationQuaternion.copyFrom(rotation);
  19293. }
  19294. else {
  19295. rotation.toEulerAnglesToRef(this.rotation);
  19296. }
  19297. this.scaling.x = scale.x;
  19298. this.scaling.y = scale.y;
  19299. this.scaling.z = scale.z;
  19300. this.position.x = position.x;
  19301. this.position.y = position.y;
  19302. this.position.z = position.z;
  19303. }
  19304. else {
  19305. var rotation = BABYLON.Tmp.Quaternion[0];
  19306. var position = BABYLON.Tmp.Vector3[0];
  19307. var scale = BABYLON.Tmp.Vector3[1];
  19308. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19309. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19310. this.computeWorldMatrix(true);
  19311. node.computeWorldMatrix(true);
  19312. node.getWorldMatrix().invertToRef(invParentMatrix);
  19313. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19314. diffMatrix.decompose(scale, rotation, position);
  19315. if (this.rotationQuaternion) {
  19316. this.rotationQuaternion.copyFrom(rotation);
  19317. }
  19318. else {
  19319. rotation.toEulerAnglesToRef(this.rotation);
  19320. }
  19321. this.position.x = position.x;
  19322. this.position.y = position.y;
  19323. this.position.z = position.z;
  19324. this.scaling.x = scale.x;
  19325. this.scaling.y = scale.y;
  19326. this.scaling.z = scale.z;
  19327. }
  19328. this.parent = node;
  19329. return this;
  19330. };
  19331. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19332. get: function () {
  19333. return this._nonUniformScaling;
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. /** @hidden */
  19339. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19340. if (this._nonUniformScaling === value) {
  19341. return false;
  19342. }
  19343. this._nonUniformScaling = value;
  19344. return true;
  19345. };
  19346. /**
  19347. * Attach the current TransformNode to another TransformNode associated with a bone
  19348. * @param bone Bone affecting the TransformNode
  19349. * @param affectedTransformNode TransformNode associated with the bone
  19350. */
  19351. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19352. this._transformToBoneReferal = affectedTransformNode;
  19353. this.parent = bone;
  19354. if (bone.getWorldMatrix().determinant() < 0) {
  19355. this.scalingDeterminant *= -1;
  19356. }
  19357. return this;
  19358. };
  19359. TransformNode.prototype.detachFromBone = function () {
  19360. if (!this.parent) {
  19361. return this;
  19362. }
  19363. if (this.parent.getWorldMatrix().determinant() < 0) {
  19364. this.scalingDeterminant *= -1;
  19365. }
  19366. this._transformToBoneReferal = null;
  19367. this.parent = null;
  19368. return this;
  19369. };
  19370. /**
  19371. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19372. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19373. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19374. * The passed axis is also normalized.
  19375. * Returns the TransformNode.
  19376. */
  19377. TransformNode.prototype.rotate = function (axis, amount, space) {
  19378. axis.normalize();
  19379. if (!this.rotationQuaternion) {
  19380. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19381. this.rotation = BABYLON.Vector3.Zero();
  19382. }
  19383. var rotationQuaternion;
  19384. if (!space || space === BABYLON.Space.LOCAL) {
  19385. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19386. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19387. }
  19388. else {
  19389. if (this.parent) {
  19390. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19391. invertParentWorldMatrix.invert();
  19392. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19393. }
  19394. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19395. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19396. }
  19397. return this;
  19398. };
  19399. /**
  19400. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19401. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19402. * The passed axis is also normalized.
  19403. * Returns the TransformNode.
  19404. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19405. */
  19406. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19407. axis.normalize();
  19408. if (!this.rotationQuaternion) {
  19409. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19410. this.rotation.copyFromFloats(0, 0, 0);
  19411. }
  19412. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19413. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19414. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19415. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19416. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19417. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19418. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19419. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19420. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19421. return this;
  19422. };
  19423. /**
  19424. * Translates the mesh along the axis vector for the passed distance in the given space.
  19425. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19426. * Returns the TransformNode.
  19427. */
  19428. TransformNode.prototype.translate = function (axis, distance, space) {
  19429. var displacementVector = axis.scale(distance);
  19430. if (!space || space === BABYLON.Space.LOCAL) {
  19431. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19432. this.setPositionWithLocalVector(tempV3);
  19433. }
  19434. else {
  19435. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19436. }
  19437. return this;
  19438. };
  19439. /**
  19440. * Adds a rotation step to the mesh current rotation.
  19441. * x, y, z are Euler angles expressed in radians.
  19442. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19443. * This means this rotation is made in the mesh local space only.
  19444. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19445. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19446. * ```javascript
  19447. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19448. * ```
  19449. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19450. * 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.
  19451. * Returns the TransformNode.
  19452. */
  19453. TransformNode.prototype.addRotation = function (x, y, z) {
  19454. var rotationQuaternion;
  19455. if (this.rotationQuaternion) {
  19456. rotationQuaternion = this.rotationQuaternion;
  19457. }
  19458. else {
  19459. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19460. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19461. }
  19462. var accumulation = BABYLON.Tmp.Quaternion[0];
  19463. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19464. rotationQuaternion.multiplyInPlace(accumulation);
  19465. if (!this.rotationQuaternion) {
  19466. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19467. }
  19468. return this;
  19469. };
  19470. /**
  19471. * Computes the world matrix of the node
  19472. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19473. * @returns the world matrix
  19474. */
  19475. TransformNode.prototype.computeWorldMatrix = function (force) {
  19476. if (this._isWorldMatrixFrozen) {
  19477. return this._worldMatrix;
  19478. }
  19479. if (!force && this.isSynchronized()) {
  19480. this._currentRenderId = this.getScene().getRenderId();
  19481. return this._worldMatrix;
  19482. }
  19483. this._updateCache();
  19484. this._cache.position.copyFrom(this.position);
  19485. this._cache.scaling.copyFrom(this.scaling);
  19486. this._cache.pivotMatrixUpdated = false;
  19487. this._cache.billboardMode = this.billboardMode;
  19488. this._currentRenderId = this.getScene().getRenderId();
  19489. this._childRenderId = this.getScene().getRenderId();
  19490. this._isDirty = false;
  19491. // Scaling
  19492. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19493. // Rotation
  19494. //rotate, if quaternion is set and rotation was used
  19495. if (this.rotationQuaternion) {
  19496. var len = this.rotation.length();
  19497. if (len) {
  19498. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19499. this.rotation.copyFromFloats(0, 0, 0);
  19500. }
  19501. }
  19502. if (this.rotationQuaternion) {
  19503. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19504. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19505. }
  19506. else {
  19507. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19508. this._cache.rotation.copyFrom(this.rotation);
  19509. }
  19510. // Translation
  19511. var camera = this.getScene().activeCamera;
  19512. if (this.infiniteDistance && !this.parent && camera) {
  19513. var cameraWorldMatrix = camera.getWorldMatrix();
  19514. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19515. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19516. }
  19517. else {
  19518. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19519. }
  19520. // Composing transformations
  19521. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19522. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19523. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19524. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19525. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19526. // Need to decompose each rotation here
  19527. var currentPosition = BABYLON.Tmp.Vector3[3];
  19528. if (this.parent && this.parent.getWorldMatrix) {
  19529. if (this._transformToBoneReferal) {
  19530. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19531. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19532. }
  19533. else {
  19534. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19535. }
  19536. }
  19537. else {
  19538. currentPosition.copyFrom(this.position);
  19539. }
  19540. currentPosition.subtractInPlace(camera.globalPosition);
  19541. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19542. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19543. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19544. }
  19545. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19546. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19547. }
  19548. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19549. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19550. }
  19551. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19552. }
  19553. else {
  19554. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19555. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19556. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19557. }
  19558. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19559. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19560. }
  19561. // Post multiply inverse of pivotMatrix
  19562. if (this._postMultiplyPivotMatrix) {
  19563. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19564. }
  19565. // Local world
  19566. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19567. // Parent
  19568. if (this.parent && this.parent.getWorldMatrix) {
  19569. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19570. if (this._transformToBoneReferal) {
  19571. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19572. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19573. }
  19574. else {
  19575. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19576. }
  19577. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19578. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19579. this._worldMatrix.copyFrom(this._localWorld);
  19580. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19581. }
  19582. else {
  19583. if (this._transformToBoneReferal) {
  19584. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19585. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19586. }
  19587. else {
  19588. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19589. }
  19590. }
  19591. this._markSyncedWithParent();
  19592. }
  19593. else {
  19594. this._worldMatrix.copyFrom(this._localWorld);
  19595. }
  19596. // Normal matrix
  19597. if (!this.ignoreNonUniformScaling) {
  19598. if (this.scaling.isNonUniform) {
  19599. this._updateNonUniformScalingState(true);
  19600. }
  19601. else if (this.parent && this.parent._nonUniformScaling) {
  19602. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19603. }
  19604. else {
  19605. this._updateNonUniformScalingState(false);
  19606. }
  19607. }
  19608. else {
  19609. this._updateNonUniformScalingState(false);
  19610. }
  19611. this._afterComputeWorldMatrix();
  19612. // Absolute position
  19613. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19614. // Callbacks
  19615. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19616. if (!this._poseMatrix) {
  19617. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19618. }
  19619. // Cache the determinant
  19620. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19621. return this._worldMatrix;
  19622. };
  19623. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19624. };
  19625. /**
  19626. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19627. * @param func: callback function to add
  19628. *
  19629. * Returns the TransformNode.
  19630. */
  19631. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19632. this.onAfterWorldMatrixUpdateObservable.add(func);
  19633. return this;
  19634. };
  19635. /**
  19636. * Removes a registered callback function.
  19637. * Returns the TransformNode.
  19638. */
  19639. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19640. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19641. return this;
  19642. };
  19643. /**
  19644. * Clone the current transform node
  19645. * Returns the new transform node
  19646. * @param name Name of the new clone
  19647. * @param newParent New parent for the clone
  19648. * @param doNotCloneChildren Do not clone children hierarchy
  19649. */
  19650. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19651. var _this = this;
  19652. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19653. result.name = name;
  19654. result.id = name;
  19655. if (newParent) {
  19656. result.parent = newParent;
  19657. }
  19658. if (!doNotCloneChildren) {
  19659. // Children
  19660. var directDescendants = this.getDescendants(true);
  19661. for (var index = 0; index < directDescendants.length; index++) {
  19662. var child = directDescendants[index];
  19663. if (child.clone) {
  19664. child.clone(name + "." + child.name, result);
  19665. }
  19666. }
  19667. }
  19668. return result;
  19669. };
  19670. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19671. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19672. serializationObject.type = this.getClassName();
  19673. // Parent
  19674. if (this.parent) {
  19675. serializationObject.parentId = this.parent.id;
  19676. }
  19677. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19678. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19679. }
  19680. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19681. serializationObject.isEnabled = this.isEnabled();
  19682. // Parent
  19683. if (this.parent) {
  19684. serializationObject.parentId = this.parent.id;
  19685. }
  19686. return serializationObject;
  19687. };
  19688. // Statics
  19689. /**
  19690. * Returns a new TransformNode object parsed from the source provided.
  19691. * The parameter `parsedMesh` is the source.
  19692. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19693. */
  19694. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19695. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19696. if (BABYLON.Tags) {
  19697. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19698. }
  19699. if (parsedTransformNode.localMatrix) {
  19700. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19701. }
  19702. else if (parsedTransformNode.pivotMatrix) {
  19703. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19704. }
  19705. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19706. // Parent
  19707. if (parsedTransformNode.parentId) {
  19708. transformNode._waitingParentId = parsedTransformNode.parentId;
  19709. }
  19710. return transformNode;
  19711. };
  19712. /**
  19713. * Releases resources associated with this transform node.
  19714. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19715. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19716. */
  19717. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19718. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19719. // Animations
  19720. this.getScene().stopAnimation(this);
  19721. // Remove from scene
  19722. this.getScene().removeTransformNode(this);
  19723. this.onAfterWorldMatrixUpdateObservable.clear();
  19724. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19725. };
  19726. // Statics
  19727. TransformNode.BILLBOARDMODE_NONE = 0;
  19728. TransformNode.BILLBOARDMODE_X = 1;
  19729. TransformNode.BILLBOARDMODE_Y = 2;
  19730. TransformNode.BILLBOARDMODE_Z = 4;
  19731. TransformNode.BILLBOARDMODE_ALL = 7;
  19732. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19733. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19734. __decorate([
  19735. BABYLON.serializeAsVector3("position")
  19736. ], TransformNode.prototype, "_position", void 0);
  19737. __decorate([
  19738. BABYLON.serializeAsVector3("rotation")
  19739. ], TransformNode.prototype, "_rotation", void 0);
  19740. __decorate([
  19741. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19742. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19743. __decorate([
  19744. BABYLON.serializeAsVector3("scaling")
  19745. ], TransformNode.prototype, "_scaling", void 0);
  19746. __decorate([
  19747. BABYLON.serialize()
  19748. ], TransformNode.prototype, "billboardMode", void 0);
  19749. __decorate([
  19750. BABYLON.serialize()
  19751. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19752. __decorate([
  19753. BABYLON.serialize()
  19754. ], TransformNode.prototype, "infiniteDistance", void 0);
  19755. __decorate([
  19756. BABYLON.serialize()
  19757. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19758. return TransformNode;
  19759. }(BABYLON.Node));
  19760. BABYLON.TransformNode = TransformNode;
  19761. })(BABYLON || (BABYLON = {}));
  19762. //# sourceMappingURL=babylon.transformNode.js.map
  19763. var BABYLON;
  19764. (function (BABYLON) {
  19765. /**
  19766. * Class used to store all common mesh properties
  19767. */
  19768. var AbstractMesh = /** @class */ (function (_super) {
  19769. __extends(AbstractMesh, _super);
  19770. // Constructor
  19771. /**
  19772. * Creates a new AbstractMesh
  19773. * @param name defines the name of the mesh
  19774. * @param scene defines the hosting scene
  19775. */
  19776. function AbstractMesh(name, scene) {
  19777. if (scene === void 0) { scene = null; }
  19778. var _this = _super.call(this, name, scene, false) || this;
  19779. _this._facetNb = 0; // facet number
  19780. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19781. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19782. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19783. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19784. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19785. _this._subDiv = {
  19786. max: 1,
  19787. X: 1,
  19788. Y: 1,
  19789. Z: 1
  19790. };
  19791. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19792. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19793. /** Gets ot sets the culling strategy to use to find visible meshes */
  19794. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19795. // Events
  19796. /**
  19797. * An event triggered when this mesh collides with another one
  19798. */
  19799. _this.onCollideObservable = new BABYLON.Observable();
  19800. /**
  19801. * An event triggered when the collision's position changes
  19802. */
  19803. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19804. /**
  19805. * An event triggered when material is changed
  19806. */
  19807. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19808. // Properties
  19809. /**
  19810. * Gets or sets the orientation for POV movement & rotation
  19811. */
  19812. _this.definedFacingForward = true;
  19813. /**
  19814. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19815. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19816. * * 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.
  19817. * @see http://doc.babylonjs.com/features/occlusionquery
  19818. */
  19819. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19820. /**
  19821. * 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:
  19822. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19823. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19824. * * 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.
  19825. * @see http://doc.babylonjs.com/features/occlusionquery
  19826. */
  19827. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19828. /**
  19829. * 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.
  19830. * The default value is -1 which means don't break the query and wait till the result
  19831. * @see http://doc.babylonjs.com/features/occlusionquery
  19832. */
  19833. _this.occlusionRetryCount = -1;
  19834. /** @hidden */
  19835. _this._occlusionInternalRetryCounter = 0;
  19836. /** @hidden */
  19837. _this._isOccluded = false;
  19838. /** @hidden */
  19839. _this._isOcclusionQueryInProgress = false;
  19840. _this._visibility = 1.0;
  19841. /** Gets or sets the alpha index used to sort transparent meshes
  19842. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19843. */
  19844. _this.alphaIndex = Number.MAX_VALUE;
  19845. /**
  19846. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19847. */
  19848. _this.isVisible = true;
  19849. /**
  19850. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19851. */
  19852. _this.isPickable = true;
  19853. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19854. _this.showSubMeshesBoundingBox = false;
  19855. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19856. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19857. */
  19858. _this.isBlocker = false;
  19859. /**
  19860. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19861. */
  19862. _this.enablePointerMoveEvents = false;
  19863. /**
  19864. * Specifies the rendering group id for this mesh (0 by default)
  19865. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19866. */
  19867. _this.renderingGroupId = 0;
  19868. _this._receiveShadows = false;
  19869. /** Defines color to use when rendering outline */
  19870. _this.outlineColor = BABYLON.Color3.Red();
  19871. /** Define width to use when rendering outline */
  19872. _this.outlineWidth = 0.02;
  19873. /** Defines color to use when rendering overlay */
  19874. _this.overlayColor = BABYLON.Color3.Red();
  19875. /** Defines alpha to use when rendering overlay */
  19876. _this.overlayAlpha = 0.5;
  19877. _this._hasVertexAlpha = false;
  19878. _this._useVertexColors = true;
  19879. _this._computeBonesUsingShaders = true;
  19880. _this._numBoneInfluencers = 4;
  19881. _this._applyFog = true;
  19882. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19883. _this.useOctreeForRenderingSelection = true;
  19884. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19885. _this.useOctreeForPicking = true;
  19886. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19887. _this.useOctreeForCollisions = true;
  19888. _this._layerMask = 0x0FFFFFFF;
  19889. /**
  19890. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19891. */
  19892. _this.alwaysSelectAsActiveMesh = false;
  19893. /**
  19894. * Gets or sets the current action manager
  19895. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19896. */
  19897. _this.actionManager = null;
  19898. // Collisions
  19899. _this._checkCollisions = false;
  19900. _this._collisionMask = -1;
  19901. _this._collisionGroup = -1;
  19902. /**
  19903. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19904. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19905. */
  19906. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19907. /**
  19908. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19909. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19910. */
  19911. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19912. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19913. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19914. // Edges
  19915. /**
  19916. * Defines edge width used when edgesRenderer is enabled
  19917. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19918. */
  19919. _this.edgesWidth = 1;
  19920. /**
  19921. * Defines edge color used when edgesRenderer is enabled
  19922. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19923. */
  19924. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19925. // Cache
  19926. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19927. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19928. /** @hidden */
  19929. _this._renderId = 0;
  19930. /** @hidden */
  19931. _this._intersectionsInProgress = new Array();
  19932. /** @hidden */
  19933. _this._unIndexed = false;
  19934. /** @hidden */
  19935. _this._lightSources = new Array();
  19936. /**
  19937. * An event triggered when the mesh is rebuilt.
  19938. */
  19939. _this.onRebuildObservable = new BABYLON.Observable();
  19940. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19941. if (collidedMesh === void 0) { collidedMesh = null; }
  19942. //TODO move this to the collision coordinator!
  19943. if (_this.getScene().workerCollisions)
  19944. newPosition.multiplyInPlace(_this._collider._radius);
  19945. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19946. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19947. _this.position.addInPlace(_this._diffPositionForCollisions);
  19948. }
  19949. if (collidedMesh) {
  19950. _this.onCollideObservable.notifyObservers(collidedMesh);
  19951. }
  19952. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19953. };
  19954. _this.getScene().addMesh(_this);
  19955. _this._resyncLightSources();
  19956. return _this;
  19957. }
  19958. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19959. /**
  19960. * No billboard
  19961. */
  19962. get: function () {
  19963. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19969. /** Billboard on X axis */
  19970. get: function () {
  19971. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19977. /** Billboard on Y axis */
  19978. get: function () {
  19979. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19980. },
  19981. enumerable: true,
  19982. configurable: true
  19983. });
  19984. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19985. /** Billboard on Z axis */
  19986. get: function () {
  19987. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19988. },
  19989. enumerable: true,
  19990. configurable: true
  19991. });
  19992. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19993. /** Billboard on all axes */
  19994. get: function () {
  19995. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19996. },
  19997. enumerable: true,
  19998. configurable: true
  19999. });
  20000. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20001. /**
  20002. * Gets the number of facets in the mesh
  20003. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20004. */
  20005. get: function () {
  20006. return this._facetNb;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20012. /**
  20013. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20014. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20015. */
  20016. get: function () {
  20017. return this._partitioningSubdivisions;
  20018. },
  20019. set: function (nb) {
  20020. this._partitioningSubdivisions = nb;
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20026. /**
  20027. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20028. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20029. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20030. */
  20031. get: function () {
  20032. return this._partitioningBBoxRatio;
  20033. },
  20034. set: function (ratio) {
  20035. this._partitioningBBoxRatio = ratio;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20041. /**
  20042. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20043. * Works only for updatable meshes.
  20044. * Doesn't work with multi-materials
  20045. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20046. */
  20047. get: function () {
  20048. return this._facetDepthSort;
  20049. },
  20050. set: function (sort) {
  20051. this._facetDepthSort = sort;
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20057. /**
  20058. * The location (Vector3) where the facet depth sort must be computed from.
  20059. * By default, the active camera position.
  20060. * Used only when facet depth sort is enabled
  20061. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20062. */
  20063. get: function () {
  20064. return this._facetDepthSortFrom;
  20065. },
  20066. set: function (location) {
  20067. this._facetDepthSortFrom = location;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20073. /**
  20074. * gets a boolean indicating if facetData is enabled
  20075. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20076. */
  20077. get: function () {
  20078. return this._facetDataEnabled;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. /** @hidden */
  20084. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20085. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20086. return false;
  20087. }
  20088. this._markSubMeshesAsMiscDirty();
  20089. return true;
  20090. };
  20091. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20092. /** Set a function to call when this mesh collides with another one */
  20093. set: function (callback) {
  20094. if (this._onCollideObserver) {
  20095. this.onCollideObservable.remove(this._onCollideObserver);
  20096. }
  20097. this._onCollideObserver = this.onCollideObservable.add(callback);
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20103. /** Set a function to call when the collision's position changes */
  20104. set: function (callback) {
  20105. if (this._onCollisionPositionChangeObserver) {
  20106. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20107. }
  20108. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20114. /**
  20115. * 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
  20116. * @see http://doc.babylonjs.com/features/occlusionquery
  20117. */
  20118. get: function () {
  20119. return this._isOccluded;
  20120. },
  20121. set: function (value) {
  20122. this._isOccluded = value;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20128. /**
  20129. * Flag to check the progress status of the query
  20130. * @see http://doc.babylonjs.com/features/occlusionquery
  20131. */
  20132. get: function () {
  20133. return this._isOcclusionQueryInProgress;
  20134. },
  20135. enumerable: true,
  20136. configurable: true
  20137. });
  20138. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20139. /**
  20140. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20141. */
  20142. get: function () {
  20143. return this._visibility;
  20144. },
  20145. /**
  20146. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20147. */
  20148. set: function (value) {
  20149. if (this._visibility === value) {
  20150. return;
  20151. }
  20152. this._visibility = value;
  20153. this._markSubMeshesAsMiscDirty();
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. Object.defineProperty(AbstractMesh.prototype, "material", {
  20159. /** Gets or sets current material */
  20160. get: function () {
  20161. return this._material;
  20162. },
  20163. set: function (value) {
  20164. if (this._material === value) {
  20165. return;
  20166. }
  20167. this._material = value;
  20168. if (this.onMaterialChangedObservable.hasObservers) {
  20169. this.onMaterialChangedObservable.notifyObservers(this);
  20170. }
  20171. if (!this.subMeshes) {
  20172. return;
  20173. }
  20174. this._unBindEffect();
  20175. },
  20176. enumerable: true,
  20177. configurable: true
  20178. });
  20179. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20180. /**
  20181. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20182. * @see http://doc.babylonjs.com/babylon101/shadows
  20183. */
  20184. get: function () {
  20185. return this._receiveShadows;
  20186. },
  20187. set: function (value) {
  20188. if (this._receiveShadows === value) {
  20189. return;
  20190. }
  20191. this._receiveShadows = value;
  20192. this._markSubMeshesAsLightDirty();
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20198. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20199. get: function () {
  20200. return this._hasVertexAlpha;
  20201. },
  20202. set: function (value) {
  20203. if (this._hasVertexAlpha === value) {
  20204. return;
  20205. }
  20206. this._hasVertexAlpha = value;
  20207. this._markSubMeshesAsAttributesDirty();
  20208. this._markSubMeshesAsMiscDirty();
  20209. },
  20210. enumerable: true,
  20211. configurable: true
  20212. });
  20213. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20214. /** 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) */
  20215. get: function () {
  20216. return this._useVertexColors;
  20217. },
  20218. set: function (value) {
  20219. if (this._useVertexColors === value) {
  20220. return;
  20221. }
  20222. this._useVertexColors = value;
  20223. this._markSubMeshesAsAttributesDirty();
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20229. /**
  20230. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20231. */
  20232. get: function () {
  20233. return this._computeBonesUsingShaders;
  20234. },
  20235. set: function (value) {
  20236. if (this._computeBonesUsingShaders === value) {
  20237. return;
  20238. }
  20239. this._computeBonesUsingShaders = value;
  20240. this._markSubMeshesAsAttributesDirty();
  20241. },
  20242. enumerable: true,
  20243. configurable: true
  20244. });
  20245. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20246. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20247. get: function () {
  20248. return this._numBoneInfluencers;
  20249. },
  20250. set: function (value) {
  20251. if (this._numBoneInfluencers === value) {
  20252. return;
  20253. }
  20254. this._numBoneInfluencers = value;
  20255. this._markSubMeshesAsAttributesDirty();
  20256. },
  20257. enumerable: true,
  20258. configurable: true
  20259. });
  20260. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20261. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20262. get: function () {
  20263. return this._applyFog;
  20264. },
  20265. set: function (value) {
  20266. if (this._applyFog === value) {
  20267. return;
  20268. }
  20269. this._applyFog = value;
  20270. this._markSubMeshesAsMiscDirty();
  20271. },
  20272. enumerable: true,
  20273. configurable: true
  20274. });
  20275. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20276. /**
  20277. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20278. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20279. */
  20280. get: function () {
  20281. return this._layerMask;
  20282. },
  20283. set: function (value) {
  20284. if (value === this._layerMask) {
  20285. return;
  20286. }
  20287. this._layerMask = value;
  20288. this._resyncLightSources();
  20289. },
  20290. enumerable: true,
  20291. configurable: true
  20292. });
  20293. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20294. /**
  20295. * Gets or sets a collision mask used to mask collisions (default is -1).
  20296. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20297. */
  20298. get: function () {
  20299. return this._collisionMask;
  20300. },
  20301. set: function (mask) {
  20302. this._collisionMask = !isNaN(mask) ? mask : -1;
  20303. },
  20304. enumerable: true,
  20305. configurable: true
  20306. });
  20307. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20308. /**
  20309. * Gets or sets the current collision group mask (-1 by default).
  20310. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20311. */
  20312. get: function () {
  20313. return this._collisionGroup;
  20314. },
  20315. set: function (mask) {
  20316. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20317. },
  20318. enumerable: true,
  20319. configurable: true
  20320. });
  20321. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20322. /** @hidden */
  20323. get: function () {
  20324. return null;
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20330. get: function () {
  20331. return this._skeleton;
  20332. },
  20333. /**
  20334. * Gets or sets a skeleton to apply skining transformations
  20335. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20336. */
  20337. set: function (value) {
  20338. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20339. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20340. }
  20341. if (value && value.needInitialSkinMatrix) {
  20342. value._registerMeshWithPoseMatrix(this);
  20343. }
  20344. this._skeleton = value;
  20345. if (!this._skeleton) {
  20346. this._bonesTransformMatrices = null;
  20347. }
  20348. this._markSubMeshesAsAttributesDirty();
  20349. },
  20350. enumerable: true,
  20351. configurable: true
  20352. });
  20353. /**
  20354. * Returns the string "AbstractMesh"
  20355. * @returns "AbstractMesh"
  20356. */
  20357. AbstractMesh.prototype.getClassName = function () {
  20358. return "AbstractMesh";
  20359. };
  20360. /**
  20361. * Gets a string representation of the current mesh
  20362. * @param fullDetails defines a boolean indicating if full details must be included
  20363. * @returns a string representation of the current mesh
  20364. */
  20365. AbstractMesh.prototype.toString = function (fullDetails) {
  20366. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20367. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20368. if (this._skeleton) {
  20369. ret += ", skeleton: " + this._skeleton.name;
  20370. }
  20371. if (fullDetails) {
  20372. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20373. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20374. }
  20375. return ret;
  20376. };
  20377. /** @hidden */
  20378. AbstractMesh.prototype._rebuild = function () {
  20379. this.onRebuildObservable.notifyObservers(this);
  20380. if (this._occlusionQuery) {
  20381. this._occlusionQuery = null;
  20382. }
  20383. if (!this.subMeshes) {
  20384. return;
  20385. }
  20386. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20387. var subMesh = _a[_i];
  20388. subMesh._rebuild();
  20389. }
  20390. };
  20391. /** @hidden */
  20392. AbstractMesh.prototype._resyncLightSources = function () {
  20393. this._lightSources.length = 0;
  20394. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20395. var light = _a[_i];
  20396. if (!light.isEnabled()) {
  20397. continue;
  20398. }
  20399. if (light.canAffectMesh(this)) {
  20400. this._lightSources.push(light);
  20401. }
  20402. }
  20403. this._markSubMeshesAsLightDirty();
  20404. };
  20405. /** @hidden */
  20406. AbstractMesh.prototype._resyncLighSource = function (light) {
  20407. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20408. var index = this._lightSources.indexOf(light);
  20409. if (index === -1) {
  20410. if (!isIn) {
  20411. return;
  20412. }
  20413. this._lightSources.push(light);
  20414. }
  20415. else {
  20416. if (isIn) {
  20417. return;
  20418. }
  20419. this._lightSources.splice(index, 1);
  20420. }
  20421. this._markSubMeshesAsLightDirty();
  20422. };
  20423. /** @hidden */
  20424. AbstractMesh.prototype._unBindEffect = function () {
  20425. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20426. var subMesh = _a[_i];
  20427. subMesh.setEffect(null);
  20428. }
  20429. };
  20430. /** @hidden */
  20431. AbstractMesh.prototype._removeLightSource = function (light) {
  20432. var index = this._lightSources.indexOf(light);
  20433. if (index === -1) {
  20434. return;
  20435. }
  20436. this._lightSources.splice(index, 1);
  20437. this._markSubMeshesAsLightDirty();
  20438. };
  20439. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20440. if (!this.subMeshes) {
  20441. return;
  20442. }
  20443. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20444. var subMesh = _a[_i];
  20445. if (subMesh._materialDefines) {
  20446. func(subMesh._materialDefines);
  20447. }
  20448. }
  20449. };
  20450. /** @hidden */
  20451. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20452. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20453. };
  20454. /** @hidden */
  20455. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20456. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20457. };
  20458. /** @hidden */
  20459. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20460. if (!this.subMeshes) {
  20461. return;
  20462. }
  20463. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20464. var subMesh = _a[_i];
  20465. var material = subMesh.getMaterial();
  20466. if (material) {
  20467. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20468. }
  20469. }
  20470. };
  20471. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20472. /**
  20473. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20474. */
  20475. get: function () {
  20476. return this._scaling;
  20477. },
  20478. set: function (newScaling) {
  20479. this._scaling = newScaling;
  20480. if (this.physicsImpostor) {
  20481. this.physicsImpostor.forceUpdate();
  20482. }
  20483. },
  20484. enumerable: true,
  20485. configurable: true
  20486. });
  20487. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20488. // Methods
  20489. /**
  20490. * Returns true if the mesh is blocked. Implemented by child classes
  20491. */
  20492. get: function () {
  20493. return false;
  20494. },
  20495. enumerable: true,
  20496. configurable: true
  20497. });
  20498. /**
  20499. * Returns the mesh itself by default. Implemented by child classes
  20500. * @param camera defines the camera to use to pick the right LOD level
  20501. * @returns the currentAbstractMesh
  20502. */
  20503. AbstractMesh.prototype.getLOD = function (camera) {
  20504. return this;
  20505. };
  20506. /**
  20507. * Returns 0 by default. Implemented by child classes
  20508. * @returns an integer
  20509. */
  20510. AbstractMesh.prototype.getTotalVertices = function () {
  20511. return 0;
  20512. };
  20513. /**
  20514. * Returns null by default. Implemented by child classes
  20515. * @returns null
  20516. */
  20517. AbstractMesh.prototype.getIndices = function () {
  20518. return null;
  20519. };
  20520. /**
  20521. * Returns the array of the requested vertex data kind. Implemented by child classes
  20522. * @param kind defines the vertex data kind to use
  20523. * @returns null
  20524. */
  20525. AbstractMesh.prototype.getVerticesData = function (kind) {
  20526. return null;
  20527. };
  20528. /**
  20529. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20530. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20531. * Note that a new underlying VertexBuffer object is created each call.
  20532. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20533. * @param kind defines vertex data kind:
  20534. * * BABYLON.VertexBuffer.PositionKind
  20535. * * BABYLON.VertexBuffer.UVKind
  20536. * * BABYLON.VertexBuffer.UV2Kind
  20537. * * BABYLON.VertexBuffer.UV3Kind
  20538. * * BABYLON.VertexBuffer.UV4Kind
  20539. * * BABYLON.VertexBuffer.UV5Kind
  20540. * * BABYLON.VertexBuffer.UV6Kind
  20541. * * BABYLON.VertexBuffer.ColorKind
  20542. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20543. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20544. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20545. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20546. * @param data defines the data source
  20547. * @param updatable defines if the data must be flagged as updatable (or static)
  20548. * @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
  20549. * @returns the current mesh
  20550. */
  20551. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20552. return this;
  20553. };
  20554. /**
  20555. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20556. * If the mesh has no geometry, it is simply returned as it is.
  20557. * @param kind defines vertex data kind:
  20558. * * BABYLON.VertexBuffer.PositionKind
  20559. * * BABYLON.VertexBuffer.UVKind
  20560. * * BABYLON.VertexBuffer.UV2Kind
  20561. * * BABYLON.VertexBuffer.UV3Kind
  20562. * * BABYLON.VertexBuffer.UV4Kind
  20563. * * BABYLON.VertexBuffer.UV5Kind
  20564. * * BABYLON.VertexBuffer.UV6Kind
  20565. * * BABYLON.VertexBuffer.ColorKind
  20566. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20567. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20568. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20569. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20570. * @param data defines the data source
  20571. * @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
  20572. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20573. * @returns the current mesh
  20574. */
  20575. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20576. return this;
  20577. };
  20578. /**
  20579. * Sets the mesh indices,
  20580. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20581. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20582. * @param totalVertices Defines the total number of vertices
  20583. * @returns the current mesh
  20584. */
  20585. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20586. return this;
  20587. };
  20588. /**
  20589. * Gets a boolean indicating if specific vertex data is present
  20590. * @param kind defines the vertex data kind to use
  20591. * @returns true is data kind is present
  20592. */
  20593. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20594. return false;
  20595. };
  20596. /**
  20597. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20598. * @returns a BoundingInfo
  20599. */
  20600. AbstractMesh.prototype.getBoundingInfo = function () {
  20601. if (this._masterMesh) {
  20602. return this._masterMesh.getBoundingInfo();
  20603. }
  20604. if (!this._boundingInfo) {
  20605. // this._boundingInfo is being created here
  20606. this._updateBoundingInfo();
  20607. }
  20608. // cannot be null.
  20609. return this._boundingInfo;
  20610. };
  20611. /**
  20612. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20613. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20614. * @returns the current mesh
  20615. */
  20616. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20617. if (includeDescendants === void 0) { includeDescendants = true; }
  20618. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20619. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20620. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20621. if (maxDimension === 0) {
  20622. return this;
  20623. }
  20624. var scale = 1 / maxDimension;
  20625. this.scaling.scaleInPlace(scale);
  20626. return this;
  20627. };
  20628. /**
  20629. * Overwrite the current bounding info
  20630. * @param boundingInfo defines the new bounding info
  20631. * @returns the current mesh
  20632. */
  20633. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20634. this._boundingInfo = boundingInfo;
  20635. return this;
  20636. };
  20637. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20638. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20639. get: function () {
  20640. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20641. },
  20642. enumerable: true,
  20643. configurable: true
  20644. });
  20645. /** @hidden */
  20646. AbstractMesh.prototype._preActivate = function () {
  20647. };
  20648. /** @hidden */
  20649. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20650. };
  20651. /** @hidden */
  20652. AbstractMesh.prototype._activate = function (renderId) {
  20653. this._renderId = renderId;
  20654. };
  20655. /**
  20656. * Gets the current world matrix
  20657. * @returns a Matrix
  20658. */
  20659. AbstractMesh.prototype.getWorldMatrix = function () {
  20660. if (this._masterMesh) {
  20661. return this._masterMesh.getWorldMatrix();
  20662. }
  20663. return _super.prototype.getWorldMatrix.call(this);
  20664. };
  20665. /** @hidden */
  20666. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20667. if (this._masterMesh) {
  20668. return this._masterMesh._getWorldMatrixDeterminant();
  20669. }
  20670. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20671. };
  20672. // ================================== Point of View Movement =================================
  20673. /**
  20674. * Perform relative position change from the point of view of behind the front of the mesh.
  20675. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20676. * Supports definition of mesh facing forward or backward
  20677. * @param amountRight defines the distance on the right axis
  20678. * @param amountUp defines the distance on the up axis
  20679. * @param amountForward defines the distance on the forward axis
  20680. * @returns the current mesh
  20681. */
  20682. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20683. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20684. return this;
  20685. };
  20686. /**
  20687. * Calculate relative position change from the point of view of behind the front of the mesh.
  20688. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20689. * Supports definition of mesh facing forward or backward
  20690. * @param amountRight defines the distance on the right axis
  20691. * @param amountUp defines the distance on the up axis
  20692. * @param amountForward defines the distance on the forward axis
  20693. * @returns the new displacement vector
  20694. */
  20695. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20696. var rotMatrix = new BABYLON.Matrix();
  20697. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20698. rotQuaternion.toRotationMatrix(rotMatrix);
  20699. var translationDelta = BABYLON.Vector3.Zero();
  20700. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20702. return translationDelta;
  20703. };
  20704. // ================================== Point of View Rotation =================================
  20705. /**
  20706. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20707. * Supports definition of mesh facing forward or backward
  20708. * @param flipBack defines the flip
  20709. * @param twirlClockwise defines the twirl
  20710. * @param tiltRight defines the tilt
  20711. * @returns the current mesh
  20712. */
  20713. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20714. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20715. return this;
  20716. };
  20717. /**
  20718. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20719. * Supports definition of mesh facing forward or backward.
  20720. * @param flipBack defines the flip
  20721. * @param twirlClockwise defines the twirl
  20722. * @param tiltRight defines the tilt
  20723. * @returns the new rotation vector
  20724. */
  20725. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20726. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20727. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20728. };
  20729. /**
  20730. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20731. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20732. * @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
  20733. * @returns the new bounding vectors
  20734. */
  20735. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20736. if (includeDescendants === void 0) { includeDescendants = true; }
  20737. if (predicate === void 0) { predicate = null; }
  20738. // Ensures that all world matrix will be recomputed.
  20739. this.getScene().incrementRenderId();
  20740. this.computeWorldMatrix(true);
  20741. var min;
  20742. var max;
  20743. var boundingInfo = this.getBoundingInfo();
  20744. if (!this.subMeshes) {
  20745. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20746. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20747. }
  20748. else {
  20749. min = boundingInfo.boundingBox.minimumWorld;
  20750. max = boundingInfo.boundingBox.maximumWorld;
  20751. }
  20752. if (includeDescendants) {
  20753. var descendants = this.getDescendants(false);
  20754. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20755. var descendant = descendants_1[_i];
  20756. var childMesh = descendant;
  20757. childMesh.computeWorldMatrix(true);
  20758. // Filters meshes based on custom predicate function.
  20759. if (predicate && !predicate(childMesh)) {
  20760. continue;
  20761. }
  20762. //make sure we have the needed params to get mix and max
  20763. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20764. continue;
  20765. }
  20766. var childBoundingInfo = childMesh.getBoundingInfo();
  20767. var boundingBox = childBoundingInfo.boundingBox;
  20768. var minBox = boundingBox.minimumWorld;
  20769. var maxBox = boundingBox.maximumWorld;
  20770. BABYLON.Tools.CheckExtends(minBox, min, max);
  20771. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20772. }
  20773. }
  20774. return {
  20775. min: min,
  20776. max: max
  20777. };
  20778. };
  20779. /** @hidden */
  20780. AbstractMesh.prototype._updateBoundingInfo = function () {
  20781. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20782. this._boundingInfo.update(this.worldMatrixFromCache);
  20783. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20784. return this;
  20785. };
  20786. /** @hidden */
  20787. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20788. if (!this.subMeshes) {
  20789. return this;
  20790. }
  20791. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20792. var subMesh = this.subMeshes[subIndex];
  20793. if (!subMesh.IsGlobal) {
  20794. subMesh.updateBoundingInfo(matrix);
  20795. }
  20796. }
  20797. return this;
  20798. };
  20799. /** @hidden */
  20800. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20801. // Bounding info
  20802. this._updateBoundingInfo();
  20803. };
  20804. /**
  20805. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20806. * A mesh is in the frustum if its bounding box intersects the frustum
  20807. * @param frustumPlanes defines the frustum to test
  20808. * @returns true if the mesh is in the frustum planes
  20809. */
  20810. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20811. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20812. };
  20813. /**
  20814. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20815. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20816. * @param frustumPlanes defines the frustum to test
  20817. * @returns true if the mesh is completely in the frustum planes
  20818. */
  20819. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20820. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20821. };
  20822. /**
  20823. * True if the mesh intersects another mesh or a SolidParticle object
  20824. * @param mesh defines a target mesh or SolidParticle to test
  20825. * @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)
  20826. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20827. * @returns true if there is an intersection
  20828. */
  20829. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20830. if (precise === void 0) { precise = false; }
  20831. if (!this._boundingInfo || !mesh._boundingInfo) {
  20832. return false;
  20833. }
  20834. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20835. return true;
  20836. }
  20837. if (includeDescendants) {
  20838. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20839. var child = _a[_i];
  20840. if (child.intersectsMesh(mesh, precise, true)) {
  20841. return true;
  20842. }
  20843. }
  20844. }
  20845. return false;
  20846. };
  20847. /**
  20848. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20849. * @param point defines the point to test
  20850. * @returns true if there is an intersection
  20851. */
  20852. AbstractMesh.prototype.intersectsPoint = function (point) {
  20853. if (!this._boundingInfo) {
  20854. return false;
  20855. }
  20856. return this._boundingInfo.intersectsPoint(point);
  20857. };
  20858. /**
  20859. * Gets the position of the current mesh in camera space
  20860. * @param camera defines the camera to use
  20861. * @returns a position
  20862. */
  20863. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20864. if (camera === void 0) { camera = null; }
  20865. if (!camera) {
  20866. camera = this.getScene().activeCamera;
  20867. }
  20868. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20869. };
  20870. /**
  20871. * Returns the distance from the mesh to the active camera
  20872. * @param camera defines the camera to use
  20873. * @returns the distance
  20874. */
  20875. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20876. if (camera === void 0) { camera = null; }
  20877. if (!camera) {
  20878. camera = this.getScene().activeCamera;
  20879. }
  20880. return this.absolutePosition.subtract(camera.position).length();
  20881. };
  20882. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20883. // Collisions
  20884. /**
  20885. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20886. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20887. */
  20888. get: function () {
  20889. return this._checkCollisions;
  20890. },
  20891. set: function (collisionEnabled) {
  20892. this._checkCollisions = collisionEnabled;
  20893. if (this.getScene().workerCollisions) {
  20894. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20895. }
  20896. },
  20897. enumerable: true,
  20898. configurable: true
  20899. });
  20900. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20901. /**
  20902. * Gets Collider object used to compute collisions (not physics)
  20903. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20904. */
  20905. get: function () {
  20906. return this._collider;
  20907. },
  20908. enumerable: true,
  20909. configurable: true
  20910. });
  20911. /**
  20912. * Move the mesh using collision engine
  20913. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20914. * @param displacement defines the requested displacement vector
  20915. * @returns the current mesh
  20916. */
  20917. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20918. var globalPosition = this.getAbsolutePosition();
  20919. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20920. if (!this._collider) {
  20921. this._collider = new BABYLON.Collider();
  20922. }
  20923. this._collider._radius = this.ellipsoid;
  20924. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20925. return this;
  20926. };
  20927. // Collisions
  20928. /** @hidden */
  20929. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20930. this._generatePointsArray();
  20931. if (!this._positions) {
  20932. return this;
  20933. }
  20934. // Transformation
  20935. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20936. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20937. subMesh._lastColliderWorldVertices = [];
  20938. subMesh._trianglePlanes = [];
  20939. var start = subMesh.verticesStart;
  20940. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20941. for (var i = start; i < end; i++) {
  20942. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20943. }
  20944. }
  20945. // Collide
  20946. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20947. if (collider.collisionFound) {
  20948. collider.collidedMesh = this;
  20949. }
  20950. return this;
  20951. };
  20952. /** @hidden */
  20953. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20954. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20955. var len = subMeshes.length;
  20956. for (var index = 0; index < len; index++) {
  20957. var subMesh = subMeshes.data[index];
  20958. // Bounding test
  20959. if (len > 1 && !subMesh._checkCollision(collider))
  20960. continue;
  20961. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20962. }
  20963. return this;
  20964. };
  20965. /** @hidden */
  20966. AbstractMesh.prototype._checkCollision = function (collider) {
  20967. // Bounding box test
  20968. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20969. return this;
  20970. // Transformation matrix
  20971. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20972. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20973. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20974. return this;
  20975. };
  20976. // Picking
  20977. /** @hidden */
  20978. AbstractMesh.prototype._generatePointsArray = function () {
  20979. return false;
  20980. };
  20981. /**
  20982. * Checks if the passed Ray intersects with the mesh
  20983. * @param ray defines the ray to use
  20984. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20985. * @returns the picking info
  20986. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20987. */
  20988. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20989. var pickingInfo = new BABYLON.PickingInfo();
  20990. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20991. return pickingInfo;
  20992. }
  20993. if (!this._generatePointsArray()) {
  20994. return pickingInfo;
  20995. }
  20996. var intersectInfo = null;
  20997. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20998. var len = subMeshes.length;
  20999. for (var index = 0; index < len; index++) {
  21000. var subMesh = subMeshes.data[index];
  21001. // Bounding test
  21002. if (len > 1 && !subMesh.canIntersects(ray))
  21003. continue;
  21004. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21005. if (currentIntersectInfo) {
  21006. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21007. intersectInfo = currentIntersectInfo;
  21008. intersectInfo.subMeshId = index;
  21009. if (fastCheck) {
  21010. break;
  21011. }
  21012. }
  21013. }
  21014. }
  21015. if (intersectInfo) {
  21016. // Get picked point
  21017. var world = this.getWorldMatrix();
  21018. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21019. var direction = ray.direction.clone();
  21020. direction = direction.scale(intersectInfo.distance);
  21021. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21022. var pickedPoint = worldOrigin.add(worldDirection);
  21023. // Return result
  21024. pickingInfo.hit = true;
  21025. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21026. pickingInfo.pickedPoint = pickedPoint;
  21027. pickingInfo.pickedMesh = this;
  21028. pickingInfo.bu = intersectInfo.bu || 0;
  21029. pickingInfo.bv = intersectInfo.bv || 0;
  21030. pickingInfo.faceId = intersectInfo.faceId;
  21031. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21032. return pickingInfo;
  21033. }
  21034. return pickingInfo;
  21035. };
  21036. /**
  21037. * Clones the current mesh
  21038. * @param name defines the mesh name
  21039. * @param newParent defines the new mesh parent
  21040. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21041. * @returns the new mesh
  21042. */
  21043. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21044. return null;
  21045. };
  21046. /**
  21047. * Disposes all the submeshes of the current meshnp
  21048. * @returns the current mesh
  21049. */
  21050. AbstractMesh.prototype.releaseSubMeshes = function () {
  21051. if (this.subMeshes) {
  21052. while (this.subMeshes.length) {
  21053. this.subMeshes[0].dispose();
  21054. }
  21055. }
  21056. else {
  21057. this.subMeshes = new Array();
  21058. }
  21059. return this;
  21060. };
  21061. /**
  21062. * Releases resources associated with this abstract mesh.
  21063. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21064. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21065. */
  21066. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21067. var _this = this;
  21068. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21069. var index;
  21070. // Smart Array Retainers.
  21071. this.getScene().freeActiveMeshes();
  21072. this.getScene().freeRenderingGroups();
  21073. // Action manager
  21074. if (this.actionManager !== undefined && this.actionManager !== null) {
  21075. this.actionManager.dispose();
  21076. this.actionManager = null;
  21077. }
  21078. // Skeleton
  21079. this._skeleton = null;
  21080. // Intersections in progress
  21081. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21082. var other = this._intersectionsInProgress[index];
  21083. var pos = other._intersectionsInProgress.indexOf(this);
  21084. other._intersectionsInProgress.splice(pos, 1);
  21085. }
  21086. this._intersectionsInProgress = [];
  21087. // Lights
  21088. var lights = this.getScene().lights;
  21089. lights.forEach(function (light) {
  21090. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21091. if (meshIndex !== -1) {
  21092. light.includedOnlyMeshes.splice(meshIndex, 1);
  21093. }
  21094. meshIndex = light.excludedMeshes.indexOf(_this);
  21095. if (meshIndex !== -1) {
  21096. light.excludedMeshes.splice(meshIndex, 1);
  21097. }
  21098. // Shadow generators
  21099. var generator = light.getShadowGenerator();
  21100. if (generator) {
  21101. var shadowMap = generator.getShadowMap();
  21102. if (shadowMap && shadowMap.renderList) {
  21103. meshIndex = shadowMap.renderList.indexOf(_this);
  21104. if (meshIndex !== -1) {
  21105. shadowMap.renderList.splice(meshIndex, 1);
  21106. }
  21107. }
  21108. }
  21109. });
  21110. // SubMeshes
  21111. if (this.getClassName() !== "InstancedMesh") {
  21112. this.releaseSubMeshes();
  21113. }
  21114. // Query
  21115. var engine = this.getScene().getEngine();
  21116. if (this._occlusionQuery) {
  21117. this._isOcclusionQueryInProgress = false;
  21118. engine.deleteQuery(this._occlusionQuery);
  21119. this._occlusionQuery = null;
  21120. }
  21121. // Engine
  21122. engine.wipeCaches();
  21123. // Remove from scene
  21124. this.getScene().removeMesh(this);
  21125. if (disposeMaterialAndTextures) {
  21126. if (this.material) {
  21127. this.material.dispose(false, true);
  21128. }
  21129. }
  21130. if (!doNotRecurse) {
  21131. // Particles
  21132. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21133. if (this.getScene().particleSystems[index].emitter === this) {
  21134. this.getScene().particleSystems[index].dispose();
  21135. index--;
  21136. }
  21137. }
  21138. }
  21139. // facet data
  21140. if (this._facetDataEnabled) {
  21141. this.disableFacetData();
  21142. }
  21143. this.onAfterWorldMatrixUpdateObservable.clear();
  21144. this.onCollideObservable.clear();
  21145. this.onCollisionPositionChangeObservable.clear();
  21146. this.onRebuildObservable.clear();
  21147. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21148. };
  21149. /**
  21150. * Adds the passed mesh as a child to the current mesh
  21151. * @param mesh defines the child mesh
  21152. * @returns the current mesh
  21153. */
  21154. AbstractMesh.prototype.addChild = function (mesh) {
  21155. mesh.setParent(this);
  21156. return this;
  21157. };
  21158. /**
  21159. * Removes the passed mesh from the current mesh children list
  21160. * @param mesh defines the child mesh
  21161. * @returns the current mesh
  21162. */
  21163. AbstractMesh.prototype.removeChild = function (mesh) {
  21164. mesh.setParent(null);
  21165. return this;
  21166. };
  21167. // Facet data
  21168. /** @hidden */
  21169. AbstractMesh.prototype._initFacetData = function () {
  21170. if (!this._facetNormals) {
  21171. this._facetNormals = new Array();
  21172. }
  21173. if (!this._facetPositions) {
  21174. this._facetPositions = new Array();
  21175. }
  21176. if (!this._facetPartitioning) {
  21177. this._facetPartitioning = new Array();
  21178. }
  21179. this._facetNb = (this.getIndices().length / 3) | 0;
  21180. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21181. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21182. for (var f = 0; f < this._facetNb; f++) {
  21183. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21184. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21185. }
  21186. this._facetDataEnabled = true;
  21187. return this;
  21188. };
  21189. /**
  21190. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21191. * This method can be called within the render loop.
  21192. * 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
  21193. * @returns the current mesh
  21194. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21195. */
  21196. AbstractMesh.prototype.updateFacetData = function () {
  21197. if (!this._facetDataEnabled) {
  21198. this._initFacetData();
  21199. }
  21200. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21201. var indices = this.getIndices();
  21202. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21203. var bInfo = this.getBoundingInfo();
  21204. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21205. // init arrays, matrix and sort function on first call
  21206. this._facetDepthSortEnabled = true;
  21207. if (indices instanceof Uint16Array) {
  21208. this._depthSortedIndices = new Uint16Array(indices);
  21209. }
  21210. else if (indices instanceof Uint32Array) {
  21211. this._depthSortedIndices = new Uint32Array(indices);
  21212. }
  21213. else {
  21214. var needs32bits = false;
  21215. for (var i = 0; i < indices.length; i++) {
  21216. if (indices[i] > 65535) {
  21217. needs32bits = true;
  21218. break;
  21219. }
  21220. }
  21221. if (needs32bits) {
  21222. this._depthSortedIndices = new Uint32Array(indices);
  21223. }
  21224. else {
  21225. this._depthSortedIndices = new Uint16Array(indices);
  21226. }
  21227. }
  21228. this._facetDepthSortFunction = function (f1, f2) {
  21229. return (f2.sqDistance - f1.sqDistance);
  21230. };
  21231. if (!this._facetDepthSortFrom) {
  21232. var camera = this.getScene().activeCamera;
  21233. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21234. }
  21235. this._depthSortedFacets = [];
  21236. for (var f = 0; f < this._facetNb; f++) {
  21237. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21238. this._depthSortedFacets.push(depthSortedFacet);
  21239. }
  21240. this._invertedMatrix = BABYLON.Matrix.Identity();
  21241. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21242. }
  21243. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21244. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21245. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21246. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21247. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21248. this._subDiv.max = this._partitioningSubdivisions;
  21249. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21250. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21251. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21252. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21253. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21254. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21255. // set the parameters for ComputeNormals()
  21256. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21257. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21258. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21259. this._facetParameters.bInfo = bInfo;
  21260. this._facetParameters.bbSize = this._bbSize;
  21261. this._facetParameters.subDiv = this._subDiv;
  21262. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21263. this._facetParameters.depthSort = this._facetDepthSort;
  21264. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21265. this.computeWorldMatrix(true);
  21266. this._worldMatrix.invertToRef(this._invertedMatrix);
  21267. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21268. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21269. }
  21270. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21271. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21272. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21273. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21274. var l = (this._depthSortedIndices.length / 3) | 0;
  21275. for (var f = 0; f < l; f++) {
  21276. var sind = this._depthSortedFacets[f].ind;
  21277. this._depthSortedIndices[f * 3] = indices[sind];
  21278. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21279. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21280. }
  21281. this.updateIndices(this._depthSortedIndices);
  21282. }
  21283. return this;
  21284. };
  21285. /**
  21286. * Returns the facetLocalNormals array.
  21287. * The normals are expressed in the mesh local spac
  21288. * @returns an array of Vector3
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21290. */
  21291. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21292. if (!this._facetNormals) {
  21293. this.updateFacetData();
  21294. }
  21295. return this._facetNormals;
  21296. };
  21297. /**
  21298. * Returns the facetLocalPositions array.
  21299. * The facet positions are expressed in the mesh local space
  21300. * @returns an array of Vector3
  21301. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21302. */
  21303. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21304. if (!this._facetPositions) {
  21305. this.updateFacetData();
  21306. }
  21307. return this._facetPositions;
  21308. };
  21309. /**
  21310. * Returns the facetLocalPartioning array
  21311. * @returns an array of array of numbers
  21312. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21313. */
  21314. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21315. if (!this._facetPartitioning) {
  21316. this.updateFacetData();
  21317. }
  21318. return this._facetPartitioning;
  21319. };
  21320. /**
  21321. * Returns the i-th facet position in the world system.
  21322. * This method allocates a new Vector3 per call
  21323. * @param i defines the facet index
  21324. * @returns a new Vector3
  21325. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21326. */
  21327. AbstractMesh.prototype.getFacetPosition = function (i) {
  21328. var pos = BABYLON.Vector3.Zero();
  21329. this.getFacetPositionToRef(i, pos);
  21330. return pos;
  21331. };
  21332. /**
  21333. * Sets the reference Vector3 with the i-th facet position in the world system
  21334. * @param i defines the facet index
  21335. * @param ref defines the target vector
  21336. * @returns the current mesh
  21337. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21338. */
  21339. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21340. var localPos = (this.getFacetLocalPositions())[i];
  21341. var world = this.getWorldMatrix();
  21342. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21343. return this;
  21344. };
  21345. /**
  21346. * Returns the i-th facet normal in the world system.
  21347. * This method allocates a new Vector3 per call
  21348. * @param i defines the facet index
  21349. * @returns a new Vector3
  21350. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21351. */
  21352. AbstractMesh.prototype.getFacetNormal = function (i) {
  21353. var norm = BABYLON.Vector3.Zero();
  21354. this.getFacetNormalToRef(i, norm);
  21355. return norm;
  21356. };
  21357. /**
  21358. * Sets the reference Vector3 with the i-th facet normal in the world system
  21359. * @param i defines the facet index
  21360. * @param ref defines the target vector
  21361. * @returns the current mesh
  21362. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21363. */
  21364. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21365. var localNorm = (this.getFacetLocalNormals())[i];
  21366. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21367. return this;
  21368. };
  21369. /**
  21370. * 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)
  21371. * @param x defines x coordinate
  21372. * @param y defines y coordinate
  21373. * @param z defines z coordinate
  21374. * @returns the array of facet indexes
  21375. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21376. */
  21377. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21378. var bInfo = this.getBoundingInfo();
  21379. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21380. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21381. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21382. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21383. return null;
  21384. }
  21385. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21386. };
  21387. /**
  21388. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21389. * @param projected sets as the (x,y,z) world projection on the facet
  21390. * @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
  21391. * @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
  21392. * @param x defines x coordinate
  21393. * @param y defines y coordinate
  21394. * @param z defines z coordinate
  21395. * @returns the face index if found (or null instead)
  21396. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21397. */
  21398. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21399. if (checkFace === void 0) { checkFace = false; }
  21400. if (facing === void 0) { facing = true; }
  21401. var world = this.getWorldMatrix();
  21402. var invMat = BABYLON.Tmp.Matrix[5];
  21403. world.invertToRef(invMat);
  21404. var invVect = BABYLON.Tmp.Vector3[8];
  21405. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21406. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21407. if (projected) {
  21408. // tranform the local computed projected vector to world coordinates
  21409. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21410. }
  21411. return closest;
  21412. };
  21413. /**
  21414. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21415. * @param projected sets as the (x,y,z) local projection on the facet
  21416. * @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
  21417. * @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
  21418. * @param x defines x coordinate
  21419. * @param y defines y coordinate
  21420. * @param z defines z coordinate
  21421. * @returns the face index if found (or null instead)
  21422. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21423. */
  21424. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21425. if (checkFace === void 0) { checkFace = false; }
  21426. if (facing === void 0) { facing = true; }
  21427. var closest = null;
  21428. var tmpx = 0.0;
  21429. var tmpy = 0.0;
  21430. var tmpz = 0.0;
  21431. var d = 0.0; // tmp dot facet normal * facet position
  21432. var t0 = 0.0;
  21433. var projx = 0.0;
  21434. var projy = 0.0;
  21435. var projz = 0.0;
  21436. // Get all the facets in the same partitioning block than (x, y, z)
  21437. var facetPositions = this.getFacetLocalPositions();
  21438. var facetNormals = this.getFacetLocalNormals();
  21439. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21440. if (!facetsInBlock) {
  21441. return null;
  21442. }
  21443. // Get the closest facet to (x, y, z)
  21444. var shortest = Number.MAX_VALUE; // init distance vars
  21445. var tmpDistance = shortest;
  21446. var fib; // current facet in the block
  21447. var norm; // current facet normal
  21448. var p0; // current facet barycenter position
  21449. // loop on all the facets in the current partitioning block
  21450. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21451. fib = facetsInBlock[idx];
  21452. norm = facetNormals[fib];
  21453. p0 = facetPositions[fib];
  21454. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21455. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21456. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21457. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21458. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21459. projx = x + norm.x * t0;
  21460. projy = y + norm.y * t0;
  21461. projz = z + norm.z * t0;
  21462. tmpx = projx - x;
  21463. tmpy = projy - y;
  21464. tmpz = projz - z;
  21465. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21466. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21467. shortest = tmpDistance;
  21468. closest = fib;
  21469. if (projected) {
  21470. projected.x = projx;
  21471. projected.y = projy;
  21472. projected.z = projz;
  21473. }
  21474. }
  21475. }
  21476. }
  21477. return closest;
  21478. };
  21479. /**
  21480. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21481. * @returns the parameters
  21482. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21483. */
  21484. AbstractMesh.prototype.getFacetDataParameters = function () {
  21485. return this._facetParameters;
  21486. };
  21487. /**
  21488. * Disables the feature FacetData and frees the related memory
  21489. * @returns the current mesh
  21490. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21491. */
  21492. AbstractMesh.prototype.disableFacetData = function () {
  21493. if (this._facetDataEnabled) {
  21494. this._facetDataEnabled = false;
  21495. this._facetPositions = new Array();
  21496. this._facetNormals = new Array();
  21497. this._facetPartitioning = new Array();
  21498. this._facetParameters = null;
  21499. this._depthSortedIndices = new Uint32Array(0);
  21500. }
  21501. return this;
  21502. };
  21503. /**
  21504. * Updates the AbstractMesh indices array
  21505. * @param indices defines the data source
  21506. * @returns the current mesh
  21507. */
  21508. AbstractMesh.prototype.updateIndices = function (indices) {
  21509. return this;
  21510. };
  21511. /**
  21512. * Creates new normals data for the mesh
  21513. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21514. * @returns the current mesh
  21515. */
  21516. AbstractMesh.prototype.createNormals = function (updatable) {
  21517. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21518. var indices = this.getIndices();
  21519. var normals;
  21520. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21521. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21522. }
  21523. else {
  21524. normals = [];
  21525. }
  21526. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21527. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21528. return this;
  21529. };
  21530. /**
  21531. * Align the mesh with a normal
  21532. * @param normal defines the normal to use
  21533. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21534. * @returns the current mesh
  21535. */
  21536. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21537. if (!upDirection) {
  21538. upDirection = BABYLON.Axis.Y;
  21539. }
  21540. var axisX = BABYLON.Tmp.Vector3[0];
  21541. var axisZ = BABYLON.Tmp.Vector3[1];
  21542. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21543. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21544. if (this.rotationQuaternion) {
  21545. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21546. }
  21547. else {
  21548. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21549. }
  21550. return this;
  21551. };
  21552. /** @hidden */
  21553. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21554. this._isOccluded = false;
  21555. };
  21556. /** No occlusion */
  21557. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21558. /** Occlusion set to optimisitic */
  21559. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21560. /** Occlusion set to strict */
  21561. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21562. /** Use an accurante occlusion algorithm */
  21563. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21564. /** Use a conservative occlusion algorithm */
  21565. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21566. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21567. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21568. /** Culling strategy with bounding sphere only and then frustum culling */
  21569. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21570. return AbstractMesh;
  21571. }(BABYLON.TransformNode));
  21572. BABYLON.AbstractMesh = AbstractMesh;
  21573. })(BABYLON || (BABYLON = {}));
  21574. //# sourceMappingURL=babylon.abstractMesh.js.map
  21575. var BABYLON;
  21576. (function (BABYLON) {
  21577. /**
  21578. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21579. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21580. * 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.
  21581. */
  21582. var Light = /** @class */ (function (_super) {
  21583. __extends(Light, _super);
  21584. /**
  21585. * Creates a Light object in the scene.
  21586. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21587. * @param name The firendly name of the light
  21588. * @param scene The scene the light belongs too
  21589. */
  21590. function Light(name, scene) {
  21591. var _this = _super.call(this, name, scene) || this;
  21592. /**
  21593. * Diffuse gives the basic color to an object.
  21594. */
  21595. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21596. /**
  21597. * Specular produces a highlight color on an object.
  21598. * Note: This is note affecting PBR materials.
  21599. */
  21600. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21601. /**
  21602. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21603. * falling off base on range or angle.
  21604. * This can be set to any values in Light.FALLOFF_x.
  21605. *
  21606. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21607. * other types of materials.
  21608. */
  21609. _this.falloffType = Light.FALLOFF_DEFAULT;
  21610. /**
  21611. * Strength of the light.
  21612. * Note: By default it is define in the framework own unit.
  21613. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21614. */
  21615. _this.intensity = 1.0;
  21616. _this._range = Number.MAX_VALUE;
  21617. _this._inverseSquaredRange = 0;
  21618. /**
  21619. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21620. * of light.
  21621. */
  21622. _this._photometricScale = 1.0;
  21623. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21624. _this._radius = 0.00001;
  21625. /**
  21626. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21627. * exceeding the number allowed of the materials.
  21628. */
  21629. _this.renderPriority = 0;
  21630. _this._shadowEnabled = true;
  21631. _this._excludeWithLayerMask = 0;
  21632. _this._includeOnlyWithLayerMask = 0;
  21633. _this._lightmapMode = 0;
  21634. /**
  21635. * @hidden Internal use only.
  21636. */
  21637. _this._excludedMeshesIds = new Array();
  21638. /**
  21639. * @hidden Internal use only.
  21640. */
  21641. _this._includedOnlyMeshesIds = new Array();
  21642. _this.getScene().addLight(_this);
  21643. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21644. _this._buildUniformLayout();
  21645. _this.includedOnlyMeshes = new Array();
  21646. _this.excludedMeshes = new Array();
  21647. _this._resyncMeshes();
  21648. return _this;
  21649. }
  21650. Object.defineProperty(Light.prototype, "range", {
  21651. /**
  21652. * Defines how far from the source the light is impacting in scene units.
  21653. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21654. */
  21655. get: function () {
  21656. return this._range;
  21657. },
  21658. /**
  21659. * Defines how far from the source the light is impacting in scene units.
  21660. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21661. */
  21662. set: function (value) {
  21663. this._range = value;
  21664. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. Object.defineProperty(Light.prototype, "intensityMode", {
  21670. /**
  21671. * Gets the photometric scale used to interpret the intensity.
  21672. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21673. */
  21674. get: function () {
  21675. return this._intensityMode;
  21676. },
  21677. /**
  21678. * Sets the photometric scale used to interpret the intensity.
  21679. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21680. */
  21681. set: function (value) {
  21682. this._intensityMode = value;
  21683. this._computePhotometricScale();
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. ;
  21689. ;
  21690. Object.defineProperty(Light.prototype, "radius", {
  21691. /**
  21692. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21693. */
  21694. get: function () {
  21695. return this._radius;
  21696. },
  21697. /**
  21698. * sets the light radius used by PBR Materials to simulate soft area lights.
  21699. */
  21700. set: function (value) {
  21701. this._radius = value;
  21702. this._computePhotometricScale();
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. ;
  21708. ;
  21709. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21710. /**
  21711. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21712. * the current shadow generator.
  21713. */
  21714. get: function () {
  21715. return this._shadowEnabled;
  21716. },
  21717. /**
  21718. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21719. * the current shadow generator.
  21720. */
  21721. set: function (value) {
  21722. if (this._shadowEnabled === value) {
  21723. return;
  21724. }
  21725. this._shadowEnabled = value;
  21726. this._markMeshesAsLightDirty();
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21732. /**
  21733. * Gets the only meshes impacted by this light.
  21734. */
  21735. get: function () {
  21736. return this._includedOnlyMeshes;
  21737. },
  21738. /**
  21739. * Sets the only meshes impacted by this light.
  21740. */
  21741. set: function (value) {
  21742. this._includedOnlyMeshes = value;
  21743. this._hookArrayForIncludedOnly(value);
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21749. /**
  21750. * Gets the meshes not impacted by this light.
  21751. */
  21752. get: function () {
  21753. return this._excludedMeshes;
  21754. },
  21755. /**
  21756. * Sets the meshes not impacted by this light.
  21757. */
  21758. set: function (value) {
  21759. this._excludedMeshes = value;
  21760. this._hookArrayForExcluded(value);
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21766. /**
  21767. * Gets the layer id use to find what meshes are not impacted by the light.
  21768. * Inactive if 0
  21769. */
  21770. get: function () {
  21771. return this._excludeWithLayerMask;
  21772. },
  21773. /**
  21774. * Sets the layer id use to find what meshes are not impacted by the light.
  21775. * Inactive if 0
  21776. */
  21777. set: function (value) {
  21778. this._excludeWithLayerMask = value;
  21779. this._resyncMeshes();
  21780. },
  21781. enumerable: true,
  21782. configurable: true
  21783. });
  21784. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21785. /**
  21786. * Gets the layer id use to find what meshes are impacted by the light.
  21787. * Inactive if 0
  21788. */
  21789. get: function () {
  21790. return this._includeOnlyWithLayerMask;
  21791. },
  21792. /**
  21793. * Sets the layer id use to find what meshes are impacted by the light.
  21794. * Inactive if 0
  21795. */
  21796. set: function (value) {
  21797. this._includeOnlyWithLayerMask = value;
  21798. this._resyncMeshes();
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Light.prototype, "lightmapMode", {
  21804. /**
  21805. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21806. */
  21807. get: function () {
  21808. return this._lightmapMode;
  21809. },
  21810. /**
  21811. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21812. */
  21813. set: function (value) {
  21814. if (this._lightmapMode === value) {
  21815. return;
  21816. }
  21817. this._lightmapMode = value;
  21818. this._markMeshesAsLightDirty();
  21819. },
  21820. enumerable: true,
  21821. configurable: true
  21822. });
  21823. /**
  21824. * Returns the string "Light".
  21825. * @returns the class name
  21826. */
  21827. Light.prototype.getClassName = function () {
  21828. return "Light";
  21829. };
  21830. /**
  21831. * Converts the light information to a readable string for debug purpose.
  21832. * @param fullDetails Supports for multiple levels of logging within scene loading
  21833. * @returns the human readable light info
  21834. */
  21835. Light.prototype.toString = function (fullDetails) {
  21836. var ret = "Name: " + this.name;
  21837. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21838. if (this.animations) {
  21839. for (var i = 0; i < this.animations.length; i++) {
  21840. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21841. }
  21842. }
  21843. if (fullDetails) {
  21844. }
  21845. return ret;
  21846. };
  21847. /** @hidden */
  21848. Light.prototype._syncParentEnabledState = function () {
  21849. _super.prototype._syncParentEnabledState.call(this);
  21850. this._resyncMeshes();
  21851. };
  21852. /**
  21853. * Set the enabled state of this node.
  21854. * @param value - the new enabled state
  21855. */
  21856. Light.prototype.setEnabled = function (value) {
  21857. _super.prototype.setEnabled.call(this, value);
  21858. this._resyncMeshes();
  21859. };
  21860. /**
  21861. * Returns the Light associated shadow generator if any.
  21862. * @return the associated shadow generator.
  21863. */
  21864. Light.prototype.getShadowGenerator = function () {
  21865. return this._shadowGenerator;
  21866. };
  21867. /**
  21868. * Returns a Vector3, the absolute light position in the World.
  21869. * @returns the world space position of the light
  21870. */
  21871. Light.prototype.getAbsolutePosition = function () {
  21872. return BABYLON.Vector3.Zero();
  21873. };
  21874. /**
  21875. * Specifies if the light will affect the passed mesh.
  21876. * @param mesh The mesh to test against the light
  21877. * @return true the mesh is affected otherwise, false.
  21878. */
  21879. Light.prototype.canAffectMesh = function (mesh) {
  21880. if (!mesh) {
  21881. return true;
  21882. }
  21883. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21884. return false;
  21885. }
  21886. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21887. return false;
  21888. }
  21889. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21890. return false;
  21891. }
  21892. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21893. return false;
  21894. }
  21895. return true;
  21896. };
  21897. /**
  21898. * Sort function to order lights for rendering.
  21899. * @param a First Light object to compare to second.
  21900. * @param b Second Light object to compare first.
  21901. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21902. */
  21903. Light.CompareLightsPriority = function (a, b) {
  21904. //shadow-casting lights have priority over non-shadow-casting lights
  21905. //the renderPrioirty is a secondary sort criterion
  21906. if (a.shadowEnabled !== b.shadowEnabled) {
  21907. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21908. }
  21909. return b.renderPriority - a.renderPriority;
  21910. };
  21911. /**
  21912. * Releases resources associated with this node.
  21913. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21914. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21915. */
  21916. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21917. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21918. if (this._shadowGenerator) {
  21919. this._shadowGenerator.dispose();
  21920. this._shadowGenerator = null;
  21921. }
  21922. // Animations
  21923. this.getScene().stopAnimation(this);
  21924. // Remove from meshes
  21925. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21926. var mesh = _a[_i];
  21927. mesh._removeLightSource(this);
  21928. }
  21929. this._uniformBuffer.dispose();
  21930. // Remove from scene
  21931. this.getScene().removeLight(this);
  21932. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21933. };
  21934. /**
  21935. * Returns the light type ID (integer).
  21936. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21937. */
  21938. Light.prototype.getTypeID = function () {
  21939. return 0;
  21940. };
  21941. /**
  21942. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21943. * @returns the scaled intensity in intensity mode unit
  21944. */
  21945. Light.prototype.getScaledIntensity = function () {
  21946. return this._photometricScale * this.intensity;
  21947. };
  21948. /**
  21949. * Returns a new Light object, named "name", from the current one.
  21950. * @param name The name of the cloned light
  21951. * @returns the new created light
  21952. */
  21953. Light.prototype.clone = function (name) {
  21954. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21955. if (!constructor) {
  21956. return null;
  21957. }
  21958. return BABYLON.SerializationHelper.Clone(constructor, this);
  21959. };
  21960. /**
  21961. * Serializes the current light into a Serialization object.
  21962. * @returns the serialized object.
  21963. */
  21964. Light.prototype.serialize = function () {
  21965. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21966. // Type
  21967. serializationObject.type = this.getTypeID();
  21968. // Parent
  21969. if (this.parent) {
  21970. serializationObject.parentId = this.parent.id;
  21971. }
  21972. // Inclusion / exclusions
  21973. if (this.excludedMeshes.length > 0) {
  21974. serializationObject.excludedMeshesIds = [];
  21975. this.excludedMeshes.forEach(function (mesh) {
  21976. serializationObject.excludedMeshesIds.push(mesh.id);
  21977. });
  21978. }
  21979. if (this.includedOnlyMeshes.length > 0) {
  21980. serializationObject.includedOnlyMeshesIds = [];
  21981. this.includedOnlyMeshes.forEach(function (mesh) {
  21982. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21983. });
  21984. }
  21985. // Animations
  21986. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21987. serializationObject.ranges = this.serializeAnimationRanges();
  21988. return serializationObject;
  21989. };
  21990. /**
  21991. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21992. * This new light is named "name" and added to the passed scene.
  21993. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21994. * @param name The friendly name of the light
  21995. * @param scene The scene the new light will belong to
  21996. * @returns the constructor function
  21997. */
  21998. Light.GetConstructorFromName = function (type, name, scene) {
  21999. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22000. if (constructorFunc) {
  22001. return constructorFunc;
  22002. }
  22003. // Default to no light for none present once.
  22004. return null;
  22005. };
  22006. /**
  22007. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22008. * @param parsedLight The JSON representation of the light
  22009. * @param scene The scene to create the parsed light in
  22010. * @returns the created light after parsing
  22011. */
  22012. Light.Parse = function (parsedLight, scene) {
  22013. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22014. if (!constructor) {
  22015. return null;
  22016. }
  22017. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22018. // Inclusion / exclusions
  22019. if (parsedLight.excludedMeshesIds) {
  22020. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22021. }
  22022. if (parsedLight.includedOnlyMeshesIds) {
  22023. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22024. }
  22025. // Parent
  22026. if (parsedLight.parentId) {
  22027. light._waitingParentId = parsedLight.parentId;
  22028. }
  22029. // Animations
  22030. if (parsedLight.animations) {
  22031. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22032. var parsedAnimation = parsedLight.animations[animationIndex];
  22033. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22034. }
  22035. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22036. }
  22037. if (parsedLight.autoAnimate) {
  22038. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22039. }
  22040. return light;
  22041. };
  22042. Light.prototype._hookArrayForExcluded = function (array) {
  22043. var _this = this;
  22044. var oldPush = array.push;
  22045. array.push = function () {
  22046. var items = [];
  22047. for (var _i = 0; _i < arguments.length; _i++) {
  22048. items[_i] = arguments[_i];
  22049. }
  22050. var result = oldPush.apply(array, items);
  22051. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22052. var item = items_1[_a];
  22053. item._resyncLighSource(_this);
  22054. }
  22055. return result;
  22056. };
  22057. var oldSplice = array.splice;
  22058. array.splice = function (index, deleteCount) {
  22059. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22060. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22061. var item = deleted_1[_i];
  22062. item._resyncLighSource(_this);
  22063. }
  22064. return deleted;
  22065. };
  22066. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22067. var item = array_1[_i];
  22068. item._resyncLighSource(this);
  22069. }
  22070. };
  22071. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22072. var _this = this;
  22073. var oldPush = array.push;
  22074. array.push = function () {
  22075. var items = [];
  22076. for (var _i = 0; _i < arguments.length; _i++) {
  22077. items[_i] = arguments[_i];
  22078. }
  22079. var result = oldPush.apply(array, items);
  22080. _this._resyncMeshes();
  22081. return result;
  22082. };
  22083. var oldSplice = array.splice;
  22084. array.splice = function (index, deleteCount) {
  22085. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22086. _this._resyncMeshes();
  22087. return deleted;
  22088. };
  22089. this._resyncMeshes();
  22090. };
  22091. Light.prototype._resyncMeshes = function () {
  22092. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22093. var mesh = _a[_i];
  22094. mesh._resyncLighSource(this);
  22095. }
  22096. };
  22097. /**
  22098. * Forces the meshes to update their light related information in their rendering used effects
  22099. * @hidden Internal Use Only
  22100. */
  22101. Light.prototype._markMeshesAsLightDirty = function () {
  22102. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22103. var mesh = _a[_i];
  22104. if (mesh._lightSources.indexOf(this) !== -1) {
  22105. mesh._markSubMeshesAsLightDirty();
  22106. }
  22107. }
  22108. };
  22109. /**
  22110. * Recomputes the cached photometric scale if needed.
  22111. */
  22112. Light.prototype._computePhotometricScale = function () {
  22113. this._photometricScale = this._getPhotometricScale();
  22114. this.getScene().resetCachedMaterial();
  22115. };
  22116. /**
  22117. * Returns the Photometric Scale according to the light type and intensity mode.
  22118. */
  22119. Light.prototype._getPhotometricScale = function () {
  22120. var photometricScale = 0.0;
  22121. var lightTypeID = this.getTypeID();
  22122. //get photometric mode
  22123. var photometricMode = this.intensityMode;
  22124. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22125. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22126. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22127. }
  22128. else {
  22129. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22130. }
  22131. }
  22132. //compute photometric scale
  22133. switch (lightTypeID) {
  22134. case Light.LIGHTTYPEID_POINTLIGHT:
  22135. case Light.LIGHTTYPEID_SPOTLIGHT:
  22136. switch (photometricMode) {
  22137. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22138. photometricScale = 1.0 / (4.0 * Math.PI);
  22139. break;
  22140. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22141. photometricScale = 1.0;
  22142. break;
  22143. case Light.INTENSITYMODE_LUMINANCE:
  22144. photometricScale = this.radius * this.radius;
  22145. break;
  22146. }
  22147. break;
  22148. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22149. switch (photometricMode) {
  22150. case Light.INTENSITYMODE_ILLUMINANCE:
  22151. photometricScale = 1.0;
  22152. break;
  22153. case Light.INTENSITYMODE_LUMINANCE:
  22154. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22155. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22156. var apexAngleRadians = this.radius;
  22157. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22158. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22159. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22160. photometricScale = solidAngle;
  22161. break;
  22162. }
  22163. break;
  22164. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22165. // No fall off in hemisperic light.
  22166. photometricScale = 1.0;
  22167. break;
  22168. }
  22169. return photometricScale;
  22170. };
  22171. /**
  22172. * Reorder the light in the scene according to their defined priority.
  22173. * @hidden Internal Use Only
  22174. */
  22175. Light.prototype._reorderLightsInScene = function () {
  22176. var scene = this.getScene();
  22177. if (this._renderPriority != 0) {
  22178. scene.requireLightSorting = true;
  22179. }
  22180. this.getScene().sortLightsByPriority();
  22181. };
  22182. /**
  22183. * Falloff Default: light is falling off following the material specification:
  22184. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22185. */
  22186. Light.FALLOFF_DEFAULT = 0;
  22187. /**
  22188. * Falloff Physical: light is falling off following the inverse squared distance law.
  22189. */
  22190. Light.FALLOFF_PHYSICAL = 1;
  22191. /**
  22192. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22193. * to enhance interoperability with other engines.
  22194. */
  22195. Light.FALLOFF_GLTF = 2;
  22196. /**
  22197. * Falloff Standard: light is falling off like in the standard material
  22198. * to enhance interoperability with other materials.
  22199. */
  22200. Light.FALLOFF_STANDARD = 3;
  22201. //lightmapMode Consts
  22202. /**
  22203. * If every light affecting the material is in this lightmapMode,
  22204. * material.lightmapTexture adds or multiplies
  22205. * (depends on material.useLightmapAsShadowmap)
  22206. * after every other light calculations.
  22207. */
  22208. Light.LIGHTMAP_DEFAULT = 0;
  22209. /**
  22210. * material.lightmapTexture as only diffuse lighting from this light
  22211. * adds only specular lighting from this light
  22212. * adds dynamic shadows
  22213. */
  22214. Light.LIGHTMAP_SPECULAR = 1;
  22215. /**
  22216. * material.lightmapTexture as only lighting
  22217. * no light calculation from this light
  22218. * only adds dynamic shadows from this light
  22219. */
  22220. Light.LIGHTMAP_SHADOWSONLY = 2;
  22221. // Intensity Mode Consts
  22222. /**
  22223. * Each light type uses the default quantity according to its type:
  22224. * point/spot lights use luminous intensity
  22225. * directional lights use illuminance
  22226. */
  22227. Light.INTENSITYMODE_AUTOMATIC = 0;
  22228. /**
  22229. * lumen (lm)
  22230. */
  22231. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22232. /**
  22233. * candela (lm/sr)
  22234. */
  22235. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22236. /**
  22237. * lux (lm/m^2)
  22238. */
  22239. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22240. /**
  22241. * nit (cd/m^2)
  22242. */
  22243. Light.INTENSITYMODE_LUMINANCE = 4;
  22244. // Light types ids const.
  22245. /**
  22246. * Light type const id of the point light.
  22247. */
  22248. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22249. /**
  22250. * Light type const id of the directional light.
  22251. */
  22252. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22253. /**
  22254. * Light type const id of the spot light.
  22255. */
  22256. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22257. /**
  22258. * Light type const id of the hemispheric light.
  22259. */
  22260. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22261. __decorate([
  22262. BABYLON.serializeAsColor3()
  22263. ], Light.prototype, "diffuse", void 0);
  22264. __decorate([
  22265. BABYLON.serializeAsColor3()
  22266. ], Light.prototype, "specular", void 0);
  22267. __decorate([
  22268. BABYLON.serialize()
  22269. ], Light.prototype, "falloffType", void 0);
  22270. __decorate([
  22271. BABYLON.serialize()
  22272. ], Light.prototype, "intensity", void 0);
  22273. __decorate([
  22274. BABYLON.serialize()
  22275. ], Light.prototype, "range", null);
  22276. __decorate([
  22277. BABYLON.serialize()
  22278. ], Light.prototype, "intensityMode", null);
  22279. __decorate([
  22280. BABYLON.serialize()
  22281. ], Light.prototype, "radius", null);
  22282. __decorate([
  22283. BABYLON.serialize()
  22284. ], Light.prototype, "_renderPriority", void 0);
  22285. __decorate([
  22286. BABYLON.expandToProperty("_reorderLightsInScene")
  22287. ], Light.prototype, "renderPriority", void 0);
  22288. __decorate([
  22289. BABYLON.serialize("shadowEnabled")
  22290. ], Light.prototype, "_shadowEnabled", void 0);
  22291. __decorate([
  22292. BABYLON.serialize("excludeWithLayerMask")
  22293. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22294. __decorate([
  22295. BABYLON.serialize("includeOnlyWithLayerMask")
  22296. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22297. __decorate([
  22298. BABYLON.serialize("lightmapMode")
  22299. ], Light.prototype, "_lightmapMode", void 0);
  22300. return Light;
  22301. }(BABYLON.Node));
  22302. BABYLON.Light = Light;
  22303. })(BABYLON || (BABYLON = {}));
  22304. //# sourceMappingURL=babylon.light.js.map
  22305. var BABYLON;
  22306. (function (BABYLON) {
  22307. /**
  22308. * This is the base class of all the camera used in the application.
  22309. * @see http://doc.babylonjs.com/features/cameras
  22310. */
  22311. var Camera = /** @class */ (function (_super) {
  22312. __extends(Camera, _super);
  22313. /**
  22314. * Instantiates a new camera object.
  22315. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22316. * @see http://doc.babylonjs.com/features/cameras
  22317. * @param name Defines the name of the camera in the scene
  22318. * @param position Defines the position of the camera
  22319. * @param scene Defines the scene the camera belongs too
  22320. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22321. */
  22322. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22323. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22324. var _this = _super.call(this, name, scene) || this;
  22325. /**
  22326. * The vector the camera should consider as up.
  22327. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22328. */
  22329. _this.upVector = BABYLON.Vector3.Up();
  22330. /**
  22331. * Define the current limit on the left side for an orthographic camera
  22332. * In scene unit
  22333. */
  22334. _this.orthoLeft = null;
  22335. /**
  22336. * Define the current limit on the right side for an orthographic camera
  22337. * In scene unit
  22338. */
  22339. _this.orthoRight = null;
  22340. /**
  22341. * Define the current limit on the bottom side for an orthographic camera
  22342. * In scene unit
  22343. */
  22344. _this.orthoBottom = null;
  22345. /**
  22346. * Define the current limit on the top side for an orthographic camera
  22347. * In scene unit
  22348. */
  22349. _this.orthoTop = null;
  22350. /**
  22351. * Field Of View is set in Radians. (default is 0.8)
  22352. */
  22353. _this.fov = 0.8;
  22354. /**
  22355. * Define the minimum distance the camera can see from.
  22356. * This is important to note that the depth buffer are not infinite and the closer it starts
  22357. * the more your scene might encounter depth fighting issue.
  22358. */
  22359. _this.minZ = 1;
  22360. /**
  22361. * Define the maximum distance the camera can see to.
  22362. * This is important to note that the depth buffer are not infinite and the further it end
  22363. * the more your scene might encounter depth fighting issue.
  22364. */
  22365. _this.maxZ = 10000.0;
  22366. /**
  22367. * Define the default inertia of the camera.
  22368. * This helps giving a smooth feeling to the camera movement.
  22369. */
  22370. _this.inertia = 0.9;
  22371. /**
  22372. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22373. */
  22374. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22375. /**
  22376. * Define wether the camera is intermediate.
  22377. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22378. */
  22379. _this.isIntermediate = false;
  22380. /**
  22381. * Define the viewport of the camera.
  22382. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22383. */
  22384. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22385. /**
  22386. * Restricts the camera to viewing objects with the same layerMask.
  22387. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22388. */
  22389. _this.layerMask = 0x0FFFFFFF;
  22390. /**
  22391. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22392. */
  22393. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22394. /**
  22395. * Rig mode of the camera.
  22396. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22397. * This is normally controlled byt the camera themselves as internal use.
  22398. */
  22399. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22400. /**
  22401. * Defines the list of custom render target the camera should render to.
  22402. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22403. * else in the scene.
  22404. */
  22405. _this.customRenderTargets = new Array();
  22406. /**
  22407. * Observable triggered when the camera view matrix has changed.
  22408. */
  22409. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22410. /**
  22411. * Observable triggered when the camera Projection matrix has changed.
  22412. */
  22413. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22414. /**
  22415. * Observable triggered when the inputs have been processed.
  22416. */
  22417. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22418. /**
  22419. * Observable triggered when reset has been called and applied to the camera.
  22420. */
  22421. _this.onRestoreStateObservable = new BABYLON.Observable();
  22422. /** @hidden */
  22423. _this._rigCameras = new Array();
  22424. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22425. /** @hidden */
  22426. _this._skipRendering = false;
  22427. /** @hidden */
  22428. _this._projectionMatrix = new BABYLON.Matrix();
  22429. /** @hidden */
  22430. _this._postProcesses = new Array();
  22431. /** @hidden */
  22432. _this._activeMeshes = new BABYLON.SmartArray(256);
  22433. _this._globalPosition = BABYLON.Vector3.Zero();
  22434. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22435. _this._doNotComputeProjectionMatrix = false;
  22436. _this._transformMatrix = BABYLON.Matrix.Zero();
  22437. _this._refreshFrustumPlanes = true;
  22438. _this.getScene().addCamera(_this);
  22439. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22440. _this.getScene().activeCamera = _this;
  22441. }
  22442. _this.position = position;
  22443. return _this;
  22444. }
  22445. /**
  22446. * Store current camera state (fov, position, etc..)
  22447. * @returns the camera
  22448. */
  22449. Camera.prototype.storeState = function () {
  22450. this._stateStored = true;
  22451. this._storedFov = this.fov;
  22452. return this;
  22453. };
  22454. /**
  22455. * Restores the camera state values if it has been stored. You must call storeState() first
  22456. */
  22457. Camera.prototype._restoreStateValues = function () {
  22458. if (!this._stateStored) {
  22459. return false;
  22460. }
  22461. this.fov = this._storedFov;
  22462. return true;
  22463. };
  22464. /**
  22465. * Restored camera state. You must call storeState() first.
  22466. * @returns true if restored and false otherwise
  22467. */
  22468. Camera.prototype.restoreState = function () {
  22469. if (this._restoreStateValues()) {
  22470. this.onRestoreStateObservable.notifyObservers(this);
  22471. return true;
  22472. }
  22473. return false;
  22474. };
  22475. /**
  22476. * Gets the class name of the camera.
  22477. * @returns the class name
  22478. */
  22479. Camera.prototype.getClassName = function () {
  22480. return "Camera";
  22481. };
  22482. /**
  22483. * Gets a string representation of the camera usefull for debug purpose.
  22484. * @param fullDetails Defines that a more verboe level of logging is required
  22485. * @returns the string representation
  22486. */
  22487. Camera.prototype.toString = function (fullDetails) {
  22488. var ret = "Name: " + this.name;
  22489. ret += ", type: " + this.getClassName();
  22490. if (this.animations) {
  22491. for (var i = 0; i < this.animations.length; i++) {
  22492. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22493. }
  22494. }
  22495. if (fullDetails) {
  22496. }
  22497. return ret;
  22498. };
  22499. Object.defineProperty(Camera.prototype, "globalPosition", {
  22500. /**
  22501. * Gets the current world space position of the camera.
  22502. */
  22503. get: function () {
  22504. return this._globalPosition;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. /**
  22510. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22511. * @returns the active meshe list
  22512. */
  22513. Camera.prototype.getActiveMeshes = function () {
  22514. return this._activeMeshes;
  22515. };
  22516. /**
  22517. * Check wether a mesh is part of the current active mesh list of the camera
  22518. * @param mesh Defines the mesh to check
  22519. * @returns true if active, false otherwise
  22520. */
  22521. Camera.prototype.isActiveMesh = function (mesh) {
  22522. return (this._activeMeshes.indexOf(mesh) !== -1);
  22523. };
  22524. /**
  22525. * Is this camera ready to be used/rendered
  22526. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22527. * @return true if the camera is ready
  22528. */
  22529. Camera.prototype.isReady = function (completeCheck) {
  22530. if (completeCheck === void 0) { completeCheck = false; }
  22531. if (completeCheck) {
  22532. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22533. var pp = _a[_i];
  22534. if (pp && !pp.isReady()) {
  22535. return false;
  22536. }
  22537. }
  22538. }
  22539. return _super.prototype.isReady.call(this, completeCheck);
  22540. };
  22541. /** @hidden */
  22542. Camera.prototype._initCache = function () {
  22543. _super.prototype._initCache.call(this);
  22544. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22545. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22546. this._cache.mode = undefined;
  22547. this._cache.minZ = undefined;
  22548. this._cache.maxZ = undefined;
  22549. this._cache.fov = undefined;
  22550. this._cache.fovMode = undefined;
  22551. this._cache.aspectRatio = undefined;
  22552. this._cache.orthoLeft = undefined;
  22553. this._cache.orthoRight = undefined;
  22554. this._cache.orthoBottom = undefined;
  22555. this._cache.orthoTop = undefined;
  22556. this._cache.renderWidth = undefined;
  22557. this._cache.renderHeight = undefined;
  22558. };
  22559. /** @hidden */
  22560. Camera.prototype._updateCache = function (ignoreParentClass) {
  22561. if (!ignoreParentClass) {
  22562. _super.prototype._updateCache.call(this);
  22563. }
  22564. this._cache.position.copyFrom(this.position);
  22565. this._cache.upVector.copyFrom(this.upVector);
  22566. };
  22567. /** @hidden */
  22568. Camera.prototype._isSynchronized = function () {
  22569. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22570. };
  22571. /** @hidden */
  22572. Camera.prototype._isSynchronizedViewMatrix = function () {
  22573. if (!_super.prototype._isSynchronized.call(this))
  22574. return false;
  22575. return this._cache.position.equals(this.position)
  22576. && this._cache.upVector.equals(this.upVector)
  22577. && this.isSynchronizedWithParent();
  22578. };
  22579. /** @hidden */
  22580. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22581. var check = this._cache.mode === this.mode
  22582. && this._cache.minZ === this.minZ
  22583. && this._cache.maxZ === this.maxZ;
  22584. if (!check) {
  22585. return false;
  22586. }
  22587. var engine = this.getEngine();
  22588. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22589. check = this._cache.fov === this.fov
  22590. && this._cache.fovMode === this.fovMode
  22591. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22592. }
  22593. else {
  22594. check = this._cache.orthoLeft === this.orthoLeft
  22595. && this._cache.orthoRight === this.orthoRight
  22596. && this._cache.orthoBottom === this.orthoBottom
  22597. && this._cache.orthoTop === this.orthoTop
  22598. && this._cache.renderWidth === engine.getRenderWidth()
  22599. && this._cache.renderHeight === engine.getRenderHeight();
  22600. }
  22601. return check;
  22602. };
  22603. /**
  22604. * Attach the input controls to a specific dom element to get the input from.
  22605. * @param element Defines the element the controls should be listened from
  22606. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22607. */
  22608. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22609. };
  22610. /**
  22611. * Detach the current controls from the specified dom element.
  22612. * @param element Defines the element to stop listening the inputs from
  22613. */
  22614. Camera.prototype.detachControl = function (element) {
  22615. };
  22616. /**
  22617. * Update the camera state according to the different inputs gathered during the frame.
  22618. */
  22619. Camera.prototype.update = function () {
  22620. this._checkInputs();
  22621. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22622. this._updateRigCameras();
  22623. }
  22624. };
  22625. /** @hidden */
  22626. Camera.prototype._checkInputs = function () {
  22627. this.onAfterCheckInputsObservable.notifyObservers(this);
  22628. };
  22629. Object.defineProperty(Camera.prototype, "rigCameras", {
  22630. /** @hidden */
  22631. get: function () {
  22632. return this._rigCameras;
  22633. },
  22634. enumerable: true,
  22635. configurable: true
  22636. });
  22637. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22638. get: function () {
  22639. return this._rigPostProcess;
  22640. },
  22641. enumerable: true,
  22642. configurable: true
  22643. });
  22644. /**
  22645. * Internal, gets the first post proces.
  22646. * @returns the first post process to be run on this camera.
  22647. */
  22648. Camera.prototype._getFirstPostProcess = function () {
  22649. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22650. if (this._postProcesses[ppIndex] !== null) {
  22651. return this._postProcesses[ppIndex];
  22652. }
  22653. }
  22654. return null;
  22655. };
  22656. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22657. // invalidate framebuffer
  22658. var firstPostProcess = this._getFirstPostProcess();
  22659. if (firstPostProcess) {
  22660. firstPostProcess.markTextureDirty();
  22661. }
  22662. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22663. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22664. var cam = this._rigCameras[i];
  22665. var rigPostProcess = cam._rigPostProcess;
  22666. // for VR rig, there does not have to be a post process
  22667. if (rigPostProcess) {
  22668. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22669. if (isPass) {
  22670. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22671. cam.isIntermediate = this._postProcesses.length === 0;
  22672. }
  22673. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22674. rigPostProcess.markTextureDirty();
  22675. }
  22676. else {
  22677. cam._postProcesses = this._postProcesses.slice(0);
  22678. }
  22679. }
  22680. };
  22681. /**
  22682. * Attach a post process to the camera.
  22683. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22684. * @param postProcess The post process to attach to the camera
  22685. * @param insertAt The position of the post process in case several of them are in use in the scene
  22686. * @returns the position the post process has been inserted at
  22687. */
  22688. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22689. if (insertAt === void 0) { insertAt = null; }
  22690. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22691. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22692. return 0;
  22693. }
  22694. if (insertAt == null || insertAt < 0) {
  22695. this._postProcesses.push(postProcess);
  22696. }
  22697. else if (this._postProcesses[insertAt] === null) {
  22698. this._postProcesses[insertAt] = postProcess;
  22699. }
  22700. else {
  22701. this._postProcesses.splice(insertAt, 0, postProcess);
  22702. }
  22703. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22704. return this._postProcesses.indexOf(postProcess);
  22705. };
  22706. /**
  22707. * Detach a post process to the camera.
  22708. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22709. * @param postProcess The post process to detach from the camera
  22710. */
  22711. Camera.prototype.detachPostProcess = function (postProcess) {
  22712. var idx = this._postProcesses.indexOf(postProcess);
  22713. if (idx !== -1) {
  22714. this._postProcesses[idx] = null;
  22715. }
  22716. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22717. };
  22718. /**
  22719. * Gets the current world matrix of the camera
  22720. */
  22721. Camera.prototype.getWorldMatrix = function () {
  22722. if (this._isSynchronizedViewMatrix()) {
  22723. return this._worldMatrix;
  22724. }
  22725. // Getting the the view matrix will also compute the world matrix.
  22726. this.getViewMatrix();
  22727. return this._worldMatrix;
  22728. };
  22729. /** @hidden */
  22730. Camera.prototype._getViewMatrix = function () {
  22731. return BABYLON.Matrix.Identity();
  22732. };
  22733. /**
  22734. * Gets the current view matrix of the camera.
  22735. * @param force forces the camera to recompute the matrix without looking at the cached state
  22736. * @returns the view matrix
  22737. */
  22738. Camera.prototype.getViewMatrix = function (force) {
  22739. if (!force && this._isSynchronizedViewMatrix()) {
  22740. return this._computedViewMatrix;
  22741. }
  22742. this.updateCache();
  22743. this._computedViewMatrix = this._getViewMatrix();
  22744. this._currentRenderId = this.getScene().getRenderId();
  22745. this._childRenderId = this._currentRenderId;
  22746. this._refreshFrustumPlanes = true;
  22747. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22748. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22749. }
  22750. this.onViewMatrixChangedObservable.notifyObservers(this);
  22751. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22752. return this._computedViewMatrix;
  22753. };
  22754. /**
  22755. * Freeze the projection matrix.
  22756. * It will prevent the cache check of the camera projection compute and can speed up perf
  22757. * if no parameter of the camera are meant to change
  22758. * @param projection Defines manually a projection if necessary
  22759. */
  22760. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22761. this._doNotComputeProjectionMatrix = true;
  22762. if (projection !== undefined) {
  22763. this._projectionMatrix = projection;
  22764. }
  22765. };
  22766. ;
  22767. /**
  22768. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22769. */
  22770. Camera.prototype.unfreezeProjectionMatrix = function () {
  22771. this._doNotComputeProjectionMatrix = false;
  22772. };
  22773. ;
  22774. /**
  22775. * Gets the current projection matrix of the camera.
  22776. * @param force forces the camera to recompute the matrix without looking at the cached state
  22777. * @returns the projection matrix
  22778. */
  22779. Camera.prototype.getProjectionMatrix = function (force) {
  22780. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22781. return this._projectionMatrix;
  22782. }
  22783. // Cache
  22784. this._cache.mode = this.mode;
  22785. this._cache.minZ = this.minZ;
  22786. this._cache.maxZ = this.maxZ;
  22787. // Matrix
  22788. this._refreshFrustumPlanes = true;
  22789. var engine = this.getEngine();
  22790. var scene = this.getScene();
  22791. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22792. this._cache.fov = this.fov;
  22793. this._cache.fovMode = this.fovMode;
  22794. this._cache.aspectRatio = engine.getAspectRatio(this);
  22795. if (this.minZ <= 0) {
  22796. this.minZ = 0.1;
  22797. }
  22798. if (scene.useRightHandedSystem) {
  22799. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22800. }
  22801. else {
  22802. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22803. }
  22804. }
  22805. else {
  22806. var halfWidth = engine.getRenderWidth() / 2.0;
  22807. var halfHeight = engine.getRenderHeight() / 2.0;
  22808. if (scene.useRightHandedSystem) {
  22809. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22810. }
  22811. else {
  22812. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22813. }
  22814. this._cache.orthoLeft = this.orthoLeft;
  22815. this._cache.orthoRight = this.orthoRight;
  22816. this._cache.orthoBottom = this.orthoBottom;
  22817. this._cache.orthoTop = this.orthoTop;
  22818. this._cache.renderWidth = engine.getRenderWidth();
  22819. this._cache.renderHeight = engine.getRenderHeight();
  22820. }
  22821. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22822. return this._projectionMatrix;
  22823. };
  22824. /**
  22825. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22826. * @returns a Matrix
  22827. */
  22828. Camera.prototype.getTransformationMatrix = function () {
  22829. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22830. return this._transformMatrix;
  22831. };
  22832. Camera.prototype._updateFrustumPlanes = function () {
  22833. if (!this._refreshFrustumPlanes) {
  22834. return;
  22835. }
  22836. this.getTransformationMatrix();
  22837. if (!this._frustumPlanes) {
  22838. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22839. }
  22840. else {
  22841. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22842. }
  22843. this._refreshFrustumPlanes = false;
  22844. };
  22845. /**
  22846. * Checks if a cullable object (mesh...) is in the camera frustum
  22847. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22848. * @param target The object to check
  22849. * @returns true if the object is in frustum otherwise false
  22850. */
  22851. Camera.prototype.isInFrustum = function (target) {
  22852. this._updateFrustumPlanes();
  22853. return target.isInFrustum(this._frustumPlanes);
  22854. };
  22855. /**
  22856. * Checks if a cullable object (mesh...) is in the camera frustum
  22857. * Unlike isInFrustum this cheks the full bounding box
  22858. * @param target The object to check
  22859. * @returns true if the object is in frustum otherwise false
  22860. */
  22861. Camera.prototype.isCompletelyInFrustum = function (target) {
  22862. this._updateFrustumPlanes();
  22863. return target.isCompletelyInFrustum(this._frustumPlanes);
  22864. };
  22865. /**
  22866. * Gets a ray in the forward direction from the camera.
  22867. * @param length Defines the length of the ray to create
  22868. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22869. * @param origin Defines the start point of the ray which defaults to the camera position
  22870. * @returns the forward ray
  22871. */
  22872. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22873. if (length === void 0) { length = 100; }
  22874. if (!transform) {
  22875. transform = this.getWorldMatrix();
  22876. }
  22877. if (!origin) {
  22878. origin = this.position;
  22879. }
  22880. var forward = new BABYLON.Vector3(0, 0, 1);
  22881. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22882. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22883. return new BABYLON.Ray(origin, direction, length);
  22884. };
  22885. /**
  22886. * Releases resources associated with this node.
  22887. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22888. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22889. */
  22890. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22891. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22892. // Observables
  22893. this.onViewMatrixChangedObservable.clear();
  22894. this.onProjectionMatrixChangedObservable.clear();
  22895. this.onAfterCheckInputsObservable.clear();
  22896. this.onRestoreStateObservable.clear();
  22897. // Inputs
  22898. if (this.inputs) {
  22899. this.inputs.clear();
  22900. }
  22901. // Animations
  22902. this.getScene().stopAnimation(this);
  22903. // Remove from scene
  22904. this.getScene().removeCamera(this);
  22905. while (this._rigCameras.length > 0) {
  22906. var camera = this._rigCameras.pop();
  22907. if (camera) {
  22908. camera.dispose();
  22909. }
  22910. }
  22911. // Postprocesses
  22912. if (this._rigPostProcess) {
  22913. this._rigPostProcess.dispose(this);
  22914. this._rigPostProcess = null;
  22915. this._postProcesses = [];
  22916. }
  22917. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22918. this._rigPostProcess = null;
  22919. this._postProcesses = [];
  22920. }
  22921. else {
  22922. var i = this._postProcesses.length;
  22923. while (--i >= 0) {
  22924. var postProcess = this._postProcesses[i];
  22925. if (postProcess) {
  22926. postProcess.dispose(this);
  22927. }
  22928. }
  22929. }
  22930. // Render targets
  22931. var i = this.customRenderTargets.length;
  22932. while (--i >= 0) {
  22933. this.customRenderTargets[i].dispose();
  22934. }
  22935. this.customRenderTargets = [];
  22936. // Active Meshes
  22937. this._activeMeshes.dispose();
  22938. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22939. };
  22940. Object.defineProperty(Camera.prototype, "leftCamera", {
  22941. /**
  22942. * Gets the left camera of a rig setup in case of Rigged Camera
  22943. */
  22944. get: function () {
  22945. if (this._rigCameras.length < 1) {
  22946. return null;
  22947. }
  22948. return this._rigCameras[0];
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. Object.defineProperty(Camera.prototype, "rightCamera", {
  22954. /**
  22955. * Gets the right camera of a rig setup in case of Rigged Camera
  22956. */
  22957. get: function () {
  22958. if (this._rigCameras.length < 2) {
  22959. return null;
  22960. }
  22961. return this._rigCameras[1];
  22962. },
  22963. enumerable: true,
  22964. configurable: true
  22965. });
  22966. /**
  22967. * Gets the left camera target of a rig setup in case of Rigged Camera
  22968. * @returns the target position
  22969. */
  22970. Camera.prototype.getLeftTarget = function () {
  22971. if (this._rigCameras.length < 1) {
  22972. return null;
  22973. }
  22974. return this._rigCameras[0].getTarget();
  22975. };
  22976. /**
  22977. * Gets the right camera target of a rig setup in case of Rigged Camera
  22978. * @returns the target position
  22979. */
  22980. Camera.prototype.getRightTarget = function () {
  22981. if (this._rigCameras.length < 2) {
  22982. return null;
  22983. }
  22984. return this._rigCameras[1].getTarget();
  22985. };
  22986. /**
  22987. * @hidden
  22988. */
  22989. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22990. if (this.cameraRigMode === mode) {
  22991. return;
  22992. }
  22993. while (this._rigCameras.length > 0) {
  22994. var camera = this._rigCameras.pop();
  22995. if (camera) {
  22996. camera.dispose();
  22997. }
  22998. }
  22999. this.cameraRigMode = mode;
  23000. this._cameraRigParams = {};
  23001. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23002. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23003. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23004. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23005. // create the rig cameras, unless none
  23006. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23007. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23008. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23009. if (leftCamera && rightCamera) {
  23010. this._rigCameras.push(leftCamera);
  23011. this._rigCameras.push(rightCamera);
  23012. }
  23013. }
  23014. switch (this.cameraRigMode) {
  23015. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23016. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23017. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23018. break;
  23019. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23020. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23021. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23022. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23023. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23024. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23025. break;
  23026. case Camera.RIG_MODE_VR:
  23027. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23028. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23029. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23030. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23031. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23032. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23033. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23034. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23035. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23036. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23037. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23038. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23039. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23040. if (metrics.compensateDistortion) {
  23041. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23042. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23043. }
  23044. break;
  23045. case Camera.RIG_MODE_WEBVR:
  23046. if (rigParams.vrDisplay) {
  23047. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23048. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23049. //Left eye
  23050. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23051. this._rigCameras[0].setCameraRigParameter("left", true);
  23052. //leaving this for future reference
  23053. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23054. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23055. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23056. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23057. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23058. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23059. this._rigCameras[0].parent = this;
  23060. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23061. //Right eye
  23062. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23063. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23064. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23065. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23066. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23067. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23068. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23069. this._rigCameras[1].parent = this;
  23070. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23071. if (Camera.UseAlternateWebVRRendering) {
  23072. this._rigCameras[1]._skipRendering = true;
  23073. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23074. }
  23075. }
  23076. break;
  23077. }
  23078. this._cascadePostProcessesToRigCams();
  23079. this.update();
  23080. };
  23081. Camera.prototype._getVRProjectionMatrix = function () {
  23082. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23083. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23084. return this._projectionMatrix;
  23085. };
  23086. Camera.prototype._updateCameraRotationMatrix = function () {
  23087. //Here for WebVR
  23088. };
  23089. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23090. //Here for WebVR
  23091. };
  23092. /**
  23093. * This function MUST be overwritten by the different WebVR cameras available.
  23094. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23095. */
  23096. Camera.prototype._getWebVRProjectionMatrix = function () {
  23097. return BABYLON.Matrix.Identity();
  23098. };
  23099. /**
  23100. * This function MUST be overwritten by the different WebVR cameras available.
  23101. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23102. */
  23103. Camera.prototype._getWebVRViewMatrix = function () {
  23104. return BABYLON.Matrix.Identity();
  23105. };
  23106. /** @hidden */
  23107. Camera.prototype.setCameraRigParameter = function (name, value) {
  23108. if (!this._cameraRigParams) {
  23109. this._cameraRigParams = {};
  23110. }
  23111. this._cameraRigParams[name] = value;
  23112. //provisionnally:
  23113. if (name === "interaxialDistance") {
  23114. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23115. }
  23116. };
  23117. /**
  23118. * needs to be overridden by children so sub has required properties to be copied
  23119. * @hidden
  23120. */
  23121. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23122. return null;
  23123. };
  23124. /**
  23125. * May need to be overridden by children
  23126. * @hidden
  23127. */
  23128. Camera.prototype._updateRigCameras = function () {
  23129. for (var i = 0; i < this._rigCameras.length; i++) {
  23130. this._rigCameras[i].minZ = this.minZ;
  23131. this._rigCameras[i].maxZ = this.maxZ;
  23132. this._rigCameras[i].fov = this.fov;
  23133. }
  23134. // only update viewport when ANAGLYPH
  23135. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23136. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23137. }
  23138. };
  23139. /** @hidden */
  23140. Camera.prototype._setupInputs = function () {
  23141. };
  23142. /**
  23143. * Serialiaze the camera setup to a json represention
  23144. * @returns the JSON representation
  23145. */
  23146. Camera.prototype.serialize = function () {
  23147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23148. // Type
  23149. serializationObject.type = this.getClassName();
  23150. // Parent
  23151. if (this.parent) {
  23152. serializationObject.parentId = this.parent.id;
  23153. }
  23154. if (this.inputs) {
  23155. this.inputs.serialize(serializationObject);
  23156. }
  23157. // Animations
  23158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23159. serializationObject.ranges = this.serializeAnimationRanges();
  23160. return serializationObject;
  23161. };
  23162. /**
  23163. * Clones the current camera.
  23164. * @param name The cloned camera name
  23165. * @returns the cloned camera
  23166. */
  23167. Camera.prototype.clone = function (name) {
  23168. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23169. };
  23170. /**
  23171. * Gets the direction of the camera relative to a given local axis.
  23172. * @param localAxis Defines the reference axis to provide a relative direction.
  23173. * @return the direction
  23174. */
  23175. Camera.prototype.getDirection = function (localAxis) {
  23176. var result = BABYLON.Vector3.Zero();
  23177. this.getDirectionToRef(localAxis, result);
  23178. return result;
  23179. };
  23180. /**
  23181. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23182. * @param localAxis Defines the reference axis to provide a relative direction.
  23183. * @param result Defines the vector to store the result in
  23184. */
  23185. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23186. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23187. };
  23188. /**
  23189. * Gets a camera constructor for a given camera type
  23190. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23191. * @param name The name of the camera the result will be able to instantiate
  23192. * @param scene The scene the result will construct the camera in
  23193. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23194. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23195. * @returns a factory method to construc the camera
  23196. */
  23197. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23198. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23199. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23200. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23201. interaxial_distance: interaxial_distance,
  23202. isStereoscopicSideBySide: isStereoscopicSideBySide
  23203. });
  23204. if (constructorFunc) {
  23205. return constructorFunc;
  23206. }
  23207. // Default to universal camera
  23208. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23209. };
  23210. /**
  23211. * Compute the world matrix of the camera.
  23212. * @returns the camera workd matrix
  23213. */
  23214. Camera.prototype.computeWorldMatrix = function () {
  23215. return this.getWorldMatrix();
  23216. };
  23217. /**
  23218. * Parse a JSON and creates the camera from the parsed information
  23219. * @param parsedCamera The JSON to parse
  23220. * @param scene The scene to instantiate the camera in
  23221. * @returns the newly constructed camera
  23222. */
  23223. Camera.Parse = function (parsedCamera, scene) {
  23224. var type = parsedCamera.type;
  23225. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23226. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23227. // Parent
  23228. if (parsedCamera.parentId) {
  23229. camera._waitingParentId = parsedCamera.parentId;
  23230. }
  23231. //If camera has an input manager, let it parse inputs settings
  23232. if (camera.inputs) {
  23233. camera.inputs.parse(parsedCamera);
  23234. camera._setupInputs();
  23235. }
  23236. if (camera.setPosition) { // need to force position
  23237. camera.position.copyFromFloats(0, 0, 0);
  23238. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23239. }
  23240. // Target
  23241. if (parsedCamera.target) {
  23242. if (camera.setTarget) {
  23243. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23244. }
  23245. }
  23246. // Apply 3d rig, when found
  23247. if (parsedCamera.cameraRigMode) {
  23248. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23249. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23250. }
  23251. // Animations
  23252. if (parsedCamera.animations) {
  23253. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23254. var parsedAnimation = parsedCamera.animations[animationIndex];
  23255. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23256. }
  23257. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23258. }
  23259. if (parsedCamera.autoAnimate) {
  23260. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23261. }
  23262. return camera;
  23263. };
  23264. /**
  23265. * This is the default projection mode used by the cameras.
  23266. * It helps recreating a feeling of perspective and better appreciate depth.
  23267. * This is the best way to simulate real life cameras.
  23268. */
  23269. Camera.PERSPECTIVE_CAMERA = 0;
  23270. /**
  23271. * This helps creating camera with an orthographic mode.
  23272. * 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.
  23273. */
  23274. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23275. /**
  23276. * This is the default FOV mode for perspective cameras.
  23277. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23278. */
  23279. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23280. /**
  23281. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23282. */
  23283. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23284. /**
  23285. * This specifies ther is no need for a camera rig.
  23286. * Basically only one eye is rendered corresponding to the camera.
  23287. */
  23288. Camera.RIG_MODE_NONE = 0;
  23289. /**
  23290. * Simulates a camera Rig with one blue eye and one red eye.
  23291. * This can be use with 3d blue and red glasses.
  23292. */
  23293. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23294. /**
  23295. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23296. */
  23297. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23298. /**
  23299. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23300. */
  23301. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23302. /**
  23303. * Defines that both eyes of the camera will be rendered over under each other.
  23304. */
  23305. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23306. /**
  23307. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23308. */
  23309. Camera.RIG_MODE_VR = 20;
  23310. /**
  23311. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23312. */
  23313. Camera.RIG_MODE_WEBVR = 21;
  23314. /**
  23315. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23316. */
  23317. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23318. /**
  23319. * @hidden
  23320. * Might be removed once multiview will be a thing
  23321. */
  23322. Camera.UseAlternateWebVRRendering = false;
  23323. __decorate([
  23324. BABYLON.serializeAsVector3()
  23325. ], Camera.prototype, "position", void 0);
  23326. __decorate([
  23327. BABYLON.serializeAsVector3()
  23328. ], Camera.prototype, "upVector", void 0);
  23329. __decorate([
  23330. BABYLON.serialize()
  23331. ], Camera.prototype, "orthoLeft", void 0);
  23332. __decorate([
  23333. BABYLON.serialize()
  23334. ], Camera.prototype, "orthoRight", void 0);
  23335. __decorate([
  23336. BABYLON.serialize()
  23337. ], Camera.prototype, "orthoBottom", void 0);
  23338. __decorate([
  23339. BABYLON.serialize()
  23340. ], Camera.prototype, "orthoTop", void 0);
  23341. __decorate([
  23342. BABYLON.serialize()
  23343. ], Camera.prototype, "fov", void 0);
  23344. __decorate([
  23345. BABYLON.serialize()
  23346. ], Camera.prototype, "minZ", void 0);
  23347. __decorate([
  23348. BABYLON.serialize()
  23349. ], Camera.prototype, "maxZ", void 0);
  23350. __decorate([
  23351. BABYLON.serialize()
  23352. ], Camera.prototype, "inertia", void 0);
  23353. __decorate([
  23354. BABYLON.serialize()
  23355. ], Camera.prototype, "mode", void 0);
  23356. __decorate([
  23357. BABYLON.serialize()
  23358. ], Camera.prototype, "layerMask", void 0);
  23359. __decorate([
  23360. BABYLON.serialize()
  23361. ], Camera.prototype, "fovMode", void 0);
  23362. __decorate([
  23363. BABYLON.serialize()
  23364. ], Camera.prototype, "cameraRigMode", void 0);
  23365. __decorate([
  23366. BABYLON.serialize()
  23367. ], Camera.prototype, "interaxialDistance", void 0);
  23368. __decorate([
  23369. BABYLON.serialize()
  23370. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23371. return Camera;
  23372. }(BABYLON.Node));
  23373. BABYLON.Camera = Camera;
  23374. })(BABYLON || (BABYLON = {}));
  23375. //# sourceMappingURL=babylon.camera.js.map
  23376. var BABYLON;
  23377. (function (BABYLON) {
  23378. /**
  23379. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23380. * It is enable to manage the different groups as well as the different necessary sort functions.
  23381. * This should not be used directly aside of the few static configurations
  23382. */
  23383. var RenderingManager = /** @class */ (function () {
  23384. /**
  23385. * Instantiates a new rendering group for a particular scene
  23386. * @param scene Defines the scene the groups belongs to
  23387. */
  23388. function RenderingManager(scene) {
  23389. /**
  23390. * @hidden
  23391. */
  23392. this._useSceneAutoClearSetup = false;
  23393. this._renderingGroups = new Array();
  23394. this._autoClearDepthStencil = {};
  23395. this._customOpaqueSortCompareFn = {};
  23396. this._customAlphaTestSortCompareFn = {};
  23397. this._customTransparentSortCompareFn = {};
  23398. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23399. this._scene = scene;
  23400. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23401. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23402. }
  23403. }
  23404. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23405. if (depth === void 0) { depth = true; }
  23406. if (stencil === void 0) { stencil = true; }
  23407. if (this._depthStencilBufferAlreadyCleaned) {
  23408. return;
  23409. }
  23410. this._scene.getEngine().clear(null, false, depth, stencil);
  23411. this._depthStencilBufferAlreadyCleaned = true;
  23412. };
  23413. /**
  23414. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23415. * @hidden
  23416. */
  23417. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23418. // Update the observable context (not null as it only goes away on dispose)
  23419. var info = this._renderingGroupInfo;
  23420. info.scene = this._scene;
  23421. info.camera = this._scene.activeCamera;
  23422. // Dispatch sprites
  23423. if (this._scene.spriteManagers && renderSprites) {
  23424. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23425. var manager = this._scene.spriteManagers[index];
  23426. this.dispatchSprites(manager);
  23427. }
  23428. }
  23429. // Render
  23430. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23431. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23432. var renderingGroup = this._renderingGroups[index];
  23433. if (!renderingGroup)
  23434. continue;
  23435. var renderingGroupMask = Math.pow(2, index);
  23436. info.renderingGroupId = index;
  23437. // Before Observable
  23438. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23439. // Clear depth/stencil if needed
  23440. if (RenderingManager.AUTOCLEAR) {
  23441. var autoClear = this._useSceneAutoClearSetup ?
  23442. this._scene.getAutoClearDepthStencilSetup(index) :
  23443. this._autoClearDepthStencil[index];
  23444. if (autoClear && autoClear.autoClear) {
  23445. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23446. }
  23447. }
  23448. // Render
  23449. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23450. var step = _a[_i];
  23451. step.action(index);
  23452. }
  23453. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23454. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23455. var step = _c[_b];
  23456. step.action(index);
  23457. }
  23458. // After Observable
  23459. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23460. }
  23461. };
  23462. /**
  23463. * Resets the different information of the group to prepare a new frame
  23464. * @hidden
  23465. */
  23466. RenderingManager.prototype.reset = function () {
  23467. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23468. var renderingGroup = this._renderingGroups[index];
  23469. if (renderingGroup) {
  23470. renderingGroup.prepare();
  23471. }
  23472. }
  23473. };
  23474. /**
  23475. * Dispose and release the group and its associated resources.
  23476. * @hidden
  23477. */
  23478. RenderingManager.prototype.dispose = function () {
  23479. this.freeRenderingGroups();
  23480. this._renderingGroups.length = 0;
  23481. this._renderingGroupInfo = null;
  23482. };
  23483. /**
  23484. * Clear the info related to rendering groups preventing retention points during dispose.
  23485. */
  23486. RenderingManager.prototype.freeRenderingGroups = function () {
  23487. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23488. var renderingGroup = this._renderingGroups[index];
  23489. if (renderingGroup) {
  23490. renderingGroup.dispose();
  23491. }
  23492. }
  23493. };
  23494. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23495. if (this._renderingGroups[renderingGroupId] === undefined) {
  23496. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23497. }
  23498. };
  23499. /**
  23500. * Add a sprite manager to the rendering manager in order to render it this frame.
  23501. * @param spriteManager Define the sprite manager to render
  23502. */
  23503. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23504. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23505. this._prepareRenderingGroup(renderingGroupId);
  23506. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23507. };
  23508. /**
  23509. * Add a particle system to the rendering manager in order to render it this frame.
  23510. * @param particleSystem Define the particle system to render
  23511. */
  23512. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23513. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23514. this._prepareRenderingGroup(renderingGroupId);
  23515. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23516. };
  23517. /**
  23518. * Add a submesh to the manager in order to render it this frame
  23519. * @param subMesh The submesh to dispatch
  23520. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23521. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23522. */
  23523. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23524. if (mesh === undefined) {
  23525. mesh = subMesh.getMesh();
  23526. }
  23527. var renderingGroupId = mesh.renderingGroupId || 0;
  23528. this._prepareRenderingGroup(renderingGroupId);
  23529. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23530. };
  23531. /**
  23532. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23533. * This allowed control for front to back rendering or reversly depending of the special needs.
  23534. *
  23535. * @param renderingGroupId The rendering group id corresponding to its index
  23536. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23537. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23538. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23539. */
  23540. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23541. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23542. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23543. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23544. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23545. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23546. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23547. if (this._renderingGroups[renderingGroupId]) {
  23548. var group = this._renderingGroups[renderingGroupId];
  23549. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23550. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23551. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23552. }
  23553. };
  23554. /**
  23555. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23556. *
  23557. * @param renderingGroupId The rendering group id corresponding to its index
  23558. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23559. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23560. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23561. */
  23562. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23563. if (depth === void 0) { depth = true; }
  23564. if (stencil === void 0) { stencil = true; }
  23565. this._autoClearDepthStencil[renderingGroupId] = {
  23566. autoClear: autoClearDepthStencil,
  23567. depth: depth,
  23568. stencil: stencil
  23569. };
  23570. };
  23571. /**
  23572. * Gets the current auto clear configuration for one rendering group of the rendering
  23573. * manager.
  23574. * @param index the rendering group index to get the information for
  23575. * @returns The auto clear setup for the requested rendering group
  23576. */
  23577. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23578. return this._autoClearDepthStencil[index];
  23579. };
  23580. /**
  23581. * The max id used for rendering groups (not included)
  23582. */
  23583. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23584. /**
  23585. * The min id used for rendering groups (included)
  23586. */
  23587. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23588. /**
  23589. * Used to globally prevent autoclearing scenes.
  23590. */
  23591. RenderingManager.AUTOCLEAR = true;
  23592. return RenderingManager;
  23593. }());
  23594. BABYLON.RenderingManager = RenderingManager;
  23595. })(BABYLON || (BABYLON = {}));
  23596. //# sourceMappingURL=babylon.renderingManager.js.map
  23597. var BABYLON;
  23598. (function (BABYLON) {
  23599. /**
  23600. * This represents the object necessary to create a rendering group.
  23601. * This is exclusively used and created by the rendering manager.
  23602. * To modify the behavior, you use the available helpers in your scene or meshes.
  23603. * @hidden
  23604. */
  23605. var RenderingGroup = /** @class */ (function () {
  23606. /**
  23607. * Creates a new rendering group.
  23608. * @param index The rendering group index
  23609. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23610. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23611. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23612. */
  23613. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23614. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23615. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23616. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23617. this.index = index;
  23618. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23619. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23620. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23621. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23622. this._particleSystems = new BABYLON.SmartArray(256);
  23623. this._spriteManagers = new BABYLON.SmartArray(256);
  23624. this._edgesRenderers = new BABYLON.SmartArray(16);
  23625. this._scene = scene;
  23626. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23627. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23628. this.transparentSortCompareFn = transparentSortCompareFn;
  23629. }
  23630. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23631. /**
  23632. * Set the opaque sort comparison function.
  23633. * If null the sub meshes will be render in the order they were created
  23634. */
  23635. set: function (value) {
  23636. this._opaqueSortCompareFn = value;
  23637. if (value) {
  23638. this._renderOpaque = this.renderOpaqueSorted;
  23639. }
  23640. else {
  23641. this._renderOpaque = RenderingGroup.renderUnsorted;
  23642. }
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23648. /**
  23649. * Set the alpha test sort comparison function.
  23650. * If null the sub meshes will be render in the order they were created
  23651. */
  23652. set: function (value) {
  23653. this._alphaTestSortCompareFn = value;
  23654. if (value) {
  23655. this._renderAlphaTest = this.renderAlphaTestSorted;
  23656. }
  23657. else {
  23658. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23659. }
  23660. },
  23661. enumerable: true,
  23662. configurable: true
  23663. });
  23664. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23665. /**
  23666. * Set the transparent sort comparison function.
  23667. * If null the sub meshes will be render in the order they were created
  23668. */
  23669. set: function (value) {
  23670. if (value) {
  23671. this._transparentSortCompareFn = value;
  23672. }
  23673. else {
  23674. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23675. }
  23676. this._renderTransparent = this.renderTransparentSorted;
  23677. },
  23678. enumerable: true,
  23679. configurable: true
  23680. });
  23681. /**
  23682. * Render all the sub meshes contained in the group.
  23683. * @param customRenderFunction Used to override the default render behaviour of the group.
  23684. * @returns true if rendered some submeshes.
  23685. */
  23686. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23687. if (customRenderFunction) {
  23688. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23689. return;
  23690. }
  23691. var engine = this._scene.getEngine();
  23692. // Depth only
  23693. if (this._depthOnlySubMeshes.length !== 0) {
  23694. engine.setColorWrite(false);
  23695. this._renderAlphaTest(this._depthOnlySubMeshes);
  23696. engine.setColorWrite(true);
  23697. }
  23698. // Opaque
  23699. if (this._opaqueSubMeshes.length !== 0) {
  23700. this._renderOpaque(this._opaqueSubMeshes);
  23701. }
  23702. // Alpha test
  23703. if (this._alphaTestSubMeshes.length !== 0) {
  23704. this._renderAlphaTest(this._alphaTestSubMeshes);
  23705. }
  23706. var stencilState = engine.getStencilBuffer();
  23707. engine.setStencilBuffer(false);
  23708. // Sprites
  23709. if (renderSprites) {
  23710. this._renderSprites();
  23711. }
  23712. // Particles
  23713. if (renderParticles) {
  23714. this._renderParticles(activeMeshes);
  23715. }
  23716. if (this.onBeforeTransparentRendering) {
  23717. this.onBeforeTransparentRendering();
  23718. }
  23719. // Transparent
  23720. if (this._transparentSubMeshes.length !== 0) {
  23721. this._renderTransparent(this._transparentSubMeshes);
  23722. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23723. }
  23724. // Set back stencil to false in case it changes before the edge renderer.
  23725. engine.setStencilBuffer(false);
  23726. // Edges
  23727. if (this._edgesRenderers.length) {
  23728. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23729. this._edgesRenderers.data[edgesRendererIndex].render();
  23730. }
  23731. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23732. }
  23733. // Restore Stencil state.
  23734. engine.setStencilBuffer(stencilState);
  23735. };
  23736. /**
  23737. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23738. * @param subMeshes The submeshes to render
  23739. */
  23740. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23741. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23742. };
  23743. /**
  23744. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23745. * @param subMeshes The submeshes to render
  23746. */
  23747. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23748. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23749. };
  23750. /**
  23751. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23752. * @param subMeshes The submeshes to render
  23753. */
  23754. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23755. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23756. };
  23757. /**
  23758. * Renders the submeshes in a specified order.
  23759. * @param subMeshes The submeshes to sort before render
  23760. * @param sortCompareFn The comparison function use to sort
  23761. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23762. * @param transparent Specifies to activate blending if true
  23763. */
  23764. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23765. var subIndex = 0;
  23766. var subMesh;
  23767. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23768. for (; subIndex < subMeshes.length; subIndex++) {
  23769. subMesh = subMeshes.data[subIndex];
  23770. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23771. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23772. }
  23773. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23774. if (sortCompareFn) {
  23775. sortedArray.sort(sortCompareFn);
  23776. }
  23777. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23778. subMesh = sortedArray[subIndex];
  23779. if (transparent) {
  23780. var material = subMesh.getMaterial();
  23781. if (material && material.needDepthPrePass) {
  23782. var engine = material.getScene().getEngine();
  23783. engine.setColorWrite(false);
  23784. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23785. subMesh.render(false);
  23786. engine.setColorWrite(true);
  23787. }
  23788. }
  23789. subMesh.render(transparent);
  23790. }
  23791. };
  23792. /**
  23793. * Renders the submeshes in the order they were dispatched (no sort applied).
  23794. * @param subMeshes The submeshes to render
  23795. */
  23796. RenderingGroup.renderUnsorted = function (subMeshes) {
  23797. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23798. var submesh = subMeshes.data[subIndex];
  23799. submesh.render(false);
  23800. }
  23801. };
  23802. /**
  23803. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23804. * are rendered back to front if in the same alpha index.
  23805. *
  23806. * @param a The first submesh
  23807. * @param b The second submesh
  23808. * @returns The result of the comparison
  23809. */
  23810. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23811. // Alpha index first
  23812. if (a._alphaIndex > b._alphaIndex) {
  23813. return 1;
  23814. }
  23815. if (a._alphaIndex < b._alphaIndex) {
  23816. return -1;
  23817. }
  23818. // Then distance to camera
  23819. return RenderingGroup.backToFrontSortCompare(a, b);
  23820. };
  23821. /**
  23822. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23823. * are rendered back to front.
  23824. *
  23825. * @param a The first submesh
  23826. * @param b The second submesh
  23827. * @returns The result of the comparison
  23828. */
  23829. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23830. // Then distance to camera
  23831. if (a._distanceToCamera < b._distanceToCamera) {
  23832. return 1;
  23833. }
  23834. if (a._distanceToCamera > b._distanceToCamera) {
  23835. return -1;
  23836. }
  23837. return 0;
  23838. };
  23839. /**
  23840. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23841. * are rendered front to back (prevent overdraw).
  23842. *
  23843. * @param a The first submesh
  23844. * @param b The second submesh
  23845. * @returns The result of the comparison
  23846. */
  23847. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23848. // Then distance to camera
  23849. if (a._distanceToCamera < b._distanceToCamera) {
  23850. return -1;
  23851. }
  23852. if (a._distanceToCamera > b._distanceToCamera) {
  23853. return 1;
  23854. }
  23855. return 0;
  23856. };
  23857. /**
  23858. * Resets the different lists of submeshes to prepare a new frame.
  23859. */
  23860. RenderingGroup.prototype.prepare = function () {
  23861. this._opaqueSubMeshes.reset();
  23862. this._transparentSubMeshes.reset();
  23863. this._alphaTestSubMeshes.reset();
  23864. this._depthOnlySubMeshes.reset();
  23865. this._particleSystems.reset();
  23866. this._spriteManagers.reset();
  23867. this._edgesRenderers.reset();
  23868. };
  23869. RenderingGroup.prototype.dispose = function () {
  23870. this._opaqueSubMeshes.dispose();
  23871. this._transparentSubMeshes.dispose();
  23872. this._alphaTestSubMeshes.dispose();
  23873. this._depthOnlySubMeshes.dispose();
  23874. this._particleSystems.dispose();
  23875. this._spriteManagers.dispose();
  23876. this._edgesRenderers.dispose();
  23877. };
  23878. /**
  23879. * Inserts the submesh in its correct queue depending on its material.
  23880. * @param subMesh The submesh to dispatch
  23881. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23882. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23883. */
  23884. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23885. // Get mesh and materials if not provided
  23886. if (mesh === undefined) {
  23887. mesh = subMesh.getMesh();
  23888. }
  23889. if (material === undefined) {
  23890. material = subMesh.getMaterial();
  23891. }
  23892. if (material === null || material === undefined) {
  23893. return;
  23894. }
  23895. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23896. this._transparentSubMeshes.push(subMesh);
  23897. }
  23898. else if (material.needAlphaTesting()) { // Alpha test
  23899. if (material.needDepthPrePass) {
  23900. this._depthOnlySubMeshes.push(subMesh);
  23901. }
  23902. this._alphaTestSubMeshes.push(subMesh);
  23903. }
  23904. else {
  23905. if (material.needDepthPrePass) {
  23906. this._depthOnlySubMeshes.push(subMesh);
  23907. }
  23908. this._opaqueSubMeshes.push(subMesh); // Opaque
  23909. }
  23910. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23911. this._edgesRenderers.push(mesh._edgesRenderer);
  23912. }
  23913. };
  23914. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23915. this._spriteManagers.push(spriteManager);
  23916. };
  23917. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23918. this._particleSystems.push(particleSystem);
  23919. };
  23920. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23921. if (this._particleSystems.length === 0) {
  23922. return;
  23923. }
  23924. // Particles
  23925. var activeCamera = this._scene.activeCamera;
  23926. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23927. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23928. var particleSystem = this._particleSystems.data[particleIndex];
  23929. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23930. continue;
  23931. }
  23932. var emitter = particleSystem.emitter;
  23933. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23934. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23935. }
  23936. }
  23937. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23938. };
  23939. RenderingGroup.prototype._renderSprites = function () {
  23940. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23941. return;
  23942. }
  23943. // Sprites
  23944. var activeCamera = this._scene.activeCamera;
  23945. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23946. for (var id = 0; id < this._spriteManagers.length; id++) {
  23947. var spriteManager = this._spriteManagers.data[id];
  23948. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23949. spriteManager.render();
  23950. }
  23951. }
  23952. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23953. };
  23954. return RenderingGroup;
  23955. }());
  23956. BABYLON.RenderingGroup = RenderingGroup;
  23957. })(BABYLON || (BABYLON = {}));
  23958. //# sourceMappingURL=babylon.renderingGroup.js.map
  23959. var BABYLON;
  23960. (function (BABYLON) {
  23961. /**
  23962. * Groups all the scene component constants in one place to ease maintenance.
  23963. * @hidden
  23964. */
  23965. var SceneComponentConstants = /** @class */ (function () {
  23966. function SceneComponentConstants() {
  23967. }
  23968. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23969. SceneComponentConstants.NAME_LAYER = "Layer";
  23970. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23971. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23972. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23973. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23974. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23975. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23976. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23977. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23978. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23979. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23980. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23981. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23982. SceneComponentConstants.NAME_OCTREE = "Octree";
  23983. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23984. SceneComponentConstants.NAME_AUDIO = "Audio";
  23985. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23986. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23987. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23988. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23989. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23990. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23991. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23992. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23993. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23994. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23995. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23996. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23997. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23998. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23999. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24000. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24001. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24002. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24003. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24004. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24005. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24006. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24007. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24008. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24009. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24010. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24011. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24012. return SceneComponentConstants;
  24013. }());
  24014. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24015. /**
  24016. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24017. * @hidden
  24018. */
  24019. var Stage = /** @class */ (function (_super) {
  24020. __extends(Stage, _super);
  24021. /**
  24022. * Hide ctor from the rest of the world.
  24023. * @param items The items to add.
  24024. */
  24025. function Stage(items) {
  24026. return _super.apply(this, items) || this;
  24027. }
  24028. /**
  24029. * Creates a new Stage.
  24030. * @returns A new instance of a Stage
  24031. */
  24032. Stage.Create = function () {
  24033. return Object.create(Stage.prototype);
  24034. };
  24035. /**
  24036. * Registers a step in an ordered way in the targeted stage.
  24037. * @param index Defines the position to register the step in
  24038. * @param component Defines the component attached to the step
  24039. * @param action Defines the action to launch during the step
  24040. */
  24041. Stage.prototype.registerStep = function (index, component, action) {
  24042. var i = 0;
  24043. var maxIndex = Number.MAX_VALUE;
  24044. for (; i < this.length && i < maxIndex; i++) {
  24045. var step = this[i];
  24046. maxIndex = step.index;
  24047. }
  24048. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24049. };
  24050. /**
  24051. * Clears all the steps from the stage.
  24052. */
  24053. Stage.prototype.clear = function () {
  24054. this.length = 0;
  24055. };
  24056. return Stage;
  24057. }(Array));
  24058. BABYLON.Stage = Stage;
  24059. })(BABYLON || (BABYLON = {}));
  24060. //# sourceMappingURL=babylon.sceneComponent.js.map
  24061. var BABYLON;
  24062. (function (BABYLON) {
  24063. /**
  24064. * Base class of the scene acting as a container for the different elements composing a scene.
  24065. * This class is dynamically extended by the different components of the scene increasing
  24066. * flexibility and reducing coupling
  24067. */
  24068. var AbstractScene = /** @class */ (function () {
  24069. function AbstractScene() {
  24070. /**
  24071. * Gets the list of root nodes (ie. nodes with no parent)
  24072. */
  24073. this.rootNodes = new Array();
  24074. /** All of the cameras added to this scene
  24075. * @see http://doc.babylonjs.com/babylon101/cameras
  24076. */
  24077. this.cameras = new Array();
  24078. /**
  24079. * All of the lights added to this scene
  24080. * @see http://doc.babylonjs.com/babylon101/lights
  24081. */
  24082. this.lights = new Array();
  24083. /**
  24084. * All of the (abstract) meshes added to this scene
  24085. */
  24086. this.meshes = new Array();
  24087. /**
  24088. * The list of skeletons added to the scene
  24089. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24090. */
  24091. this.skeletons = new Array();
  24092. /**
  24093. * All of the particle systems added to this scene
  24094. * @see http://doc.babylonjs.com/babylon101/particles
  24095. */
  24096. this.particleSystems = new Array();
  24097. /**
  24098. * Gets a list of Animations associated with the scene
  24099. */
  24100. this.animations = [];
  24101. /**
  24102. * All of the animation groups added to this scene
  24103. * @see http://doc.babylonjs.com/how_to/group
  24104. */
  24105. this.animationGroups = new Array();
  24106. /**
  24107. * All of the multi-materials added to this scene
  24108. * @see http://doc.babylonjs.com/how_to/multi_materials
  24109. */
  24110. this.multiMaterials = new Array();
  24111. /**
  24112. * All of the materials added to this scene
  24113. * @see http://doc.babylonjs.com/babylon101/materials
  24114. */
  24115. this.materials = new Array();
  24116. /**
  24117. * The list of morph target managers added to the scene
  24118. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24119. */
  24120. this.morphTargetManagers = new Array();
  24121. /**
  24122. * The list of geometries used in the scene.
  24123. */
  24124. this.geometries = new Array();
  24125. /**
  24126. * All of the tranform nodes added to this scene
  24127. * @see http://doc.babylonjs.com/how_to/transformnode
  24128. */
  24129. this.transformNodes = new Array();
  24130. /**
  24131. * ActionManagers available on the scene.
  24132. */
  24133. this.actionManagers = new Array();
  24134. /**
  24135. * Textures to keep.
  24136. */
  24137. this.textures = new Array();
  24138. }
  24139. /**
  24140. * Adds a parser in the list of available ones
  24141. * @param name Defines the name of the parser
  24142. * @param parser Defines the parser to add
  24143. */
  24144. AbstractScene.AddParser = function (name, parser) {
  24145. this._BabylonFileParsers[name] = parser;
  24146. };
  24147. /**
  24148. * Gets a general parser from the list of avaialble ones
  24149. * @param name Defines the name of the parser
  24150. * @returns the requested parser or null
  24151. */
  24152. AbstractScene.GetParser = function (name) {
  24153. if (this._BabylonFileParsers[name]) {
  24154. return this._BabylonFileParsers[name];
  24155. }
  24156. return null;
  24157. };
  24158. /**
  24159. * Adds n individual parser in the list of available ones
  24160. * @param name Defines the name of the parser
  24161. * @param parser Defines the parser to add
  24162. */
  24163. AbstractScene.AddIndividualParser = function (name, parser) {
  24164. this._IndividualBabylonFileParsers[name] = parser;
  24165. };
  24166. /**
  24167. * Gets an individual parser from the list of avaialble ones
  24168. * @param name Defines the name of the parser
  24169. * @returns the requested parser or null
  24170. */
  24171. AbstractScene.GetIndividualParser = function (name) {
  24172. if (this._IndividualBabylonFileParsers[name]) {
  24173. return this._IndividualBabylonFileParsers[name];
  24174. }
  24175. return null;
  24176. };
  24177. /**
  24178. * Parser json data and populate both a scene and its associated container object
  24179. * @param jsonData Defines the data to parse
  24180. * @param scene Defines the scene to parse the data for
  24181. * @param container Defines the container attached to the parsing sequence
  24182. * @param rootUrl Defines the root url of the data
  24183. */
  24184. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24185. for (var parserName in this._BabylonFileParsers) {
  24186. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24187. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24188. }
  24189. }
  24190. };
  24191. /**
  24192. * Stores the list of available parsers in the application.
  24193. */
  24194. AbstractScene._BabylonFileParsers = {};
  24195. /**
  24196. * Stores the list of available individual parsers in the application.
  24197. */
  24198. AbstractScene._IndividualBabylonFileParsers = {};
  24199. return AbstractScene;
  24200. }());
  24201. BABYLON.AbstractScene = AbstractScene;
  24202. })(BABYLON || (BABYLON = {}));
  24203. //# sourceMappingURL=babylon.abstractScene.js.map
  24204. var BABYLON;
  24205. (function (BABYLON) {
  24206. /** @hidden */
  24207. var ClickInfo = /** @class */ (function () {
  24208. function ClickInfo() {
  24209. this._singleClick = false;
  24210. this._doubleClick = false;
  24211. this._hasSwiped = false;
  24212. this._ignore = false;
  24213. }
  24214. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24215. get: function () {
  24216. return this._singleClick;
  24217. },
  24218. set: function (b) {
  24219. this._singleClick = b;
  24220. },
  24221. enumerable: true,
  24222. configurable: true
  24223. });
  24224. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24225. get: function () {
  24226. return this._doubleClick;
  24227. },
  24228. set: function (b) {
  24229. this._doubleClick = b;
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24235. get: function () {
  24236. return this._hasSwiped;
  24237. },
  24238. set: function (b) {
  24239. this._hasSwiped = b;
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24245. get: function () {
  24246. return this._ignore;
  24247. },
  24248. set: function (b) {
  24249. this._ignore = b;
  24250. },
  24251. enumerable: true,
  24252. configurable: true
  24253. });
  24254. return ClickInfo;
  24255. }());
  24256. /**
  24257. * This class is used by the onRenderingGroupObservable
  24258. */
  24259. var RenderingGroupInfo = /** @class */ (function () {
  24260. function RenderingGroupInfo() {
  24261. }
  24262. return RenderingGroupInfo;
  24263. }());
  24264. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24265. /**
  24266. * Represents a scene to be rendered by the engine.
  24267. * @see http://doc.babylonjs.com/features/scene
  24268. */
  24269. var Scene = /** @class */ (function (_super) {
  24270. __extends(Scene, _super);
  24271. /**
  24272. * Creates a new Scene
  24273. * @param engine defines the engine to use to render this scene
  24274. */
  24275. function Scene(engine) {
  24276. var _this = _super.call(this) || this;
  24277. // Members
  24278. /**
  24279. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24280. */
  24281. _this.autoClear = true;
  24282. /**
  24283. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24284. */
  24285. _this.autoClearDepthAndStencil = true;
  24286. /**
  24287. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24288. */
  24289. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24290. /**
  24291. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24292. */
  24293. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24294. _this._forceWireframe = false;
  24295. _this._forcePointsCloud = false;
  24296. /**
  24297. * Gets or sets a boolean indicating if animations are enabled
  24298. */
  24299. _this.animationsEnabled = true;
  24300. _this._animationPropertiesOverride = null;
  24301. /**
  24302. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24303. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24304. */
  24305. _this.useConstantAnimationDeltaTime = false;
  24306. /**
  24307. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24308. * Please note that it requires to run a ray cast through the scene on every frame
  24309. */
  24310. _this.constantlyUpdateMeshUnderPointer = false;
  24311. /**
  24312. * Defines the HTML cursor to use when hovering over interactive elements
  24313. */
  24314. _this.hoverCursor = "pointer";
  24315. /**
  24316. * Defines the HTML default cursor to use (empty by default)
  24317. */
  24318. _this.defaultCursor = "";
  24319. /**
  24320. * This is used to call preventDefault() on pointer down
  24321. * in order to block unwanted artifacts like system double clicks
  24322. */
  24323. _this.preventDefaultOnPointerDown = true;
  24324. // Metadata
  24325. /**
  24326. * Gets or sets user defined metadata
  24327. */
  24328. _this.metadata = null;
  24329. /**
  24330. * Use this array to add regular expressions used to disable offline support for specific urls
  24331. */
  24332. _this.disableOfflineSupportExceptionRules = new Array();
  24333. /**
  24334. * An event triggered when the scene is disposed.
  24335. */
  24336. _this.onDisposeObservable = new BABYLON.Observable();
  24337. _this._onDisposeObserver = null;
  24338. /**
  24339. * An event triggered before rendering the scene (right after animations and physics)
  24340. */
  24341. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24342. _this._onBeforeRenderObserver = null;
  24343. /**
  24344. * An event triggered after rendering the scene
  24345. */
  24346. _this.onAfterRenderObservable = new BABYLON.Observable();
  24347. _this._onAfterRenderObserver = null;
  24348. /**
  24349. * An event triggered before animating the scene
  24350. */
  24351. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24352. /**
  24353. * An event triggered after animations processing
  24354. */
  24355. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24356. /**
  24357. * An event triggered before draw calls are ready to be sent
  24358. */
  24359. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24360. /**
  24361. * An event triggered after draw calls have been sent
  24362. */
  24363. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24364. /**
  24365. * An event triggered when the scene is ready
  24366. */
  24367. _this.onReadyObservable = new BABYLON.Observable();
  24368. /**
  24369. * An event triggered before rendering a camera
  24370. */
  24371. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24372. _this._onBeforeCameraRenderObserver = null;
  24373. /**
  24374. * An event triggered after rendering a camera
  24375. */
  24376. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24377. _this._onAfterCameraRenderObserver = null;
  24378. /**
  24379. * An event triggered when active meshes evaluation is about to start
  24380. */
  24381. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24382. /**
  24383. * An event triggered when active meshes evaluation is done
  24384. */
  24385. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24386. /**
  24387. * An event triggered when particles rendering is about to start
  24388. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24389. */
  24390. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24391. /**
  24392. * An event triggered when particles rendering is done
  24393. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24394. */
  24395. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24396. /**
  24397. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24398. */
  24399. _this.onDataLoadedObservable = new BABYLON.Observable();
  24400. /**
  24401. * An event triggered when a camera is created
  24402. */
  24403. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24404. /**
  24405. * An event triggered when a camera is removed
  24406. */
  24407. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24408. /**
  24409. * An event triggered when a light is created
  24410. */
  24411. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24412. /**
  24413. * An event triggered when a light is removed
  24414. */
  24415. _this.onLightRemovedObservable = new BABYLON.Observable();
  24416. /**
  24417. * An event triggered when a geometry is created
  24418. */
  24419. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24420. /**
  24421. * An event triggered when a geometry is removed
  24422. */
  24423. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24424. /**
  24425. * An event triggered when a transform node is created
  24426. */
  24427. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24428. /**
  24429. * An event triggered when a transform node is removed
  24430. */
  24431. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24432. /**
  24433. * An event triggered when a mesh is created
  24434. */
  24435. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24436. /**
  24437. * An event triggered when a mesh is removed
  24438. */
  24439. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24440. /**
  24441. * An event triggered when a material is created
  24442. */
  24443. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24444. /**
  24445. * An event triggered when a material is removed
  24446. */
  24447. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24448. /**
  24449. * An event triggered when a texture is created
  24450. */
  24451. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24452. /**
  24453. * An event triggered when a texture is removed
  24454. */
  24455. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24456. /**
  24457. * An event triggered when render targets are about to be rendered
  24458. * Can happen multiple times per frame.
  24459. */
  24460. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24461. /**
  24462. * An event triggered when render targets were rendered.
  24463. * Can happen multiple times per frame.
  24464. */
  24465. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24466. /**
  24467. * An event triggered before calculating deterministic simulation step
  24468. */
  24469. _this.onBeforeStepObservable = new BABYLON.Observable();
  24470. /**
  24471. * An event triggered after calculating deterministic simulation step
  24472. */
  24473. _this.onAfterStepObservable = new BABYLON.Observable();
  24474. /**
  24475. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24476. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24477. * 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)
  24478. */
  24479. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24480. /**
  24481. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24482. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24483. * 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)
  24484. */
  24485. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24486. /**
  24487. * This Observable will when a mesh has been imported into the scene.
  24488. */
  24489. _this.onMeshImportedObservable = new BABYLON.Observable();
  24490. // Animations
  24491. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24492. /**
  24493. * 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).
  24494. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24495. */
  24496. _this.onPrePointerObservable = new BABYLON.Observable();
  24497. /**
  24498. * Observable event triggered each time an input event is received from the rendering canvas
  24499. */
  24500. _this.onPointerObservable = new BABYLON.Observable();
  24501. _this._meshPickProceed = false;
  24502. _this._currentPickResult = null;
  24503. _this._previousPickResult = null;
  24504. _this._totalPointersPressed = 0;
  24505. _this._doubleClickOccured = false;
  24506. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24507. _this.cameraToUseForPointers = null;
  24508. _this._pointerX = 0;
  24509. _this._pointerY = 0;
  24510. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24511. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24512. _this._startingPointerTime = 0;
  24513. _this._previousStartingPointerTime = 0;
  24514. _this._pointerCaptures = {};
  24515. // Deterministic lockstep
  24516. _this._timeAccumulator = 0;
  24517. _this._currentStepId = 0;
  24518. _this._currentInternalStep = 0;
  24519. // Keyboard
  24520. /**
  24521. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24522. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24523. */
  24524. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24525. /**
  24526. * Observable event triggered each time an keyboard event is received from the hosting window
  24527. */
  24528. _this.onKeyboardObservable = new BABYLON.Observable();
  24529. // Coordinates system
  24530. _this._useRightHandedSystem = false;
  24531. // Fog
  24532. _this._fogEnabled = true;
  24533. _this._fogMode = Scene.FOGMODE_NONE;
  24534. /**
  24535. * Gets or sets the fog color to use
  24536. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24537. */
  24538. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24539. /**
  24540. * Gets or sets the fog density to use
  24541. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24542. */
  24543. _this.fogDensity = 0.1;
  24544. /**
  24545. * Gets or sets the fog start distance to use
  24546. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24547. */
  24548. _this.fogStart = 0;
  24549. /**
  24550. * Gets or sets the fog end distance to use
  24551. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24552. */
  24553. _this.fogEnd = 1000.0;
  24554. // Lights
  24555. _this._shadowsEnabled = true;
  24556. _this._lightsEnabled = true;
  24557. /** All of the active cameras added to this scene. */
  24558. _this.activeCameras = new Array();
  24559. // Textures
  24560. _this._texturesEnabled = true;
  24561. // Particles
  24562. /**
  24563. * Gets or sets a boolean indicating if particles are enabled on this scene
  24564. */
  24565. _this.particlesEnabled = true;
  24566. // Sprites
  24567. /**
  24568. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24569. */
  24570. _this.spritesEnabled = true;
  24571. // Skeletons
  24572. _this._skeletonsEnabled = true;
  24573. // Lens flares
  24574. /**
  24575. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24576. */
  24577. _this.lensFlaresEnabled = true;
  24578. // Collisions
  24579. /**
  24580. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24581. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24582. */
  24583. _this.collisionsEnabled = true;
  24584. /**
  24585. * Defines the gravity applied to this scene (used only for collisions)
  24586. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24587. */
  24588. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24589. // Postprocesses
  24590. /**
  24591. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24592. */
  24593. _this.postProcessesEnabled = true;
  24594. /**
  24595. * The list of postprocesses added to the scene
  24596. */
  24597. _this.postProcesses = new Array();
  24598. // Customs render targets
  24599. /**
  24600. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24601. */
  24602. _this.renderTargetsEnabled = true;
  24603. /**
  24604. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24605. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24606. */
  24607. _this.dumpNextRenderTargets = false;
  24608. /**
  24609. * The list of user defined render targets added to the scene
  24610. */
  24611. _this.customRenderTargets = new Array();
  24612. /**
  24613. * Gets the list of meshes imported to the scene through SceneLoader
  24614. */
  24615. _this.importedMeshesFiles = new Array();
  24616. // Probes
  24617. /**
  24618. * Gets or sets a boolean indicating if probes are enabled on this scene
  24619. */
  24620. _this.probesEnabled = true;
  24621. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24622. // Procedural textures
  24623. /**
  24624. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24625. */
  24626. _this.proceduralTexturesEnabled = true;
  24627. // Performance counters
  24628. _this._totalVertices = new BABYLON.PerfCounter();
  24629. /** @hidden */
  24630. _this._activeIndices = new BABYLON.PerfCounter();
  24631. /** @hidden */
  24632. _this._activeParticles = new BABYLON.PerfCounter();
  24633. /** @hidden */
  24634. _this._activeBones = new BABYLON.PerfCounter();
  24635. _this._animationTime = 0;
  24636. /**
  24637. * Gets or sets a general scale for animation speed
  24638. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24639. */
  24640. _this.animationTimeScale = 1;
  24641. _this._renderId = 0;
  24642. _this._frameId = 0;
  24643. _this._executeWhenReadyTimeoutId = -1;
  24644. _this._intermediateRendering = false;
  24645. _this._viewUpdateFlag = -1;
  24646. _this._projectionUpdateFlag = -1;
  24647. _this._alternateViewUpdateFlag = -1;
  24648. _this._alternateProjectionUpdateFlag = -1;
  24649. /** @hidden */
  24650. _this._toBeDisposed = new Array(256);
  24651. _this._activeRequests = new Array();
  24652. _this._pendingData = new Array();
  24653. _this._isDisposed = false;
  24654. /**
  24655. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24656. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24657. */
  24658. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24659. _this._activeMeshes = new BABYLON.SmartArray(256);
  24660. _this._processedMaterials = new BABYLON.SmartArray(256);
  24661. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24662. /** @hidden */
  24663. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24664. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24665. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24666. /** @hidden */
  24667. _this._activeAnimatables = new Array();
  24668. _this._transformMatrix = BABYLON.Matrix.Zero();
  24669. _this._useAlternateCameraConfiguration = false;
  24670. _this._alternateRendering = false;
  24671. /**
  24672. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24673. * This is useful if there are more lights that the maximum simulteanous authorized
  24674. */
  24675. _this.requireLightSorting = false;
  24676. /**
  24677. * @hidden
  24678. * Backing store of defined scene components.
  24679. */
  24680. _this._components = [];
  24681. /**
  24682. * @hidden
  24683. * Backing store of defined scene components.
  24684. */
  24685. _this._serializableComponents = [];
  24686. /**
  24687. * List of components to register on the next registration step.
  24688. */
  24689. _this._transientComponents = [];
  24690. /**
  24691. * @hidden
  24692. * Defines the actions happening before camera updates.
  24693. */
  24694. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24695. /**
  24696. * @hidden
  24697. * Defines the actions happening before clear the canvas.
  24698. */
  24699. _this._beforeClearStage = BABYLON.Stage.Create();
  24700. /**
  24701. * @hidden
  24702. * Defines the actions when collecting render targets for the frame.
  24703. */
  24704. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24705. /**
  24706. * @hidden
  24707. * Defines the actions happening for one camera in the frame.
  24708. */
  24709. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24710. /**
  24711. * @hidden
  24712. * Defines the actions happening during the per mesh ready checks.
  24713. */
  24714. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24715. /**
  24716. * @hidden
  24717. * Defines the actions happening before evaluate active mesh checks.
  24718. */
  24719. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24720. /**
  24721. * @hidden
  24722. * Defines the actions happening during the evaluate sub mesh checks.
  24723. */
  24724. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24725. /**
  24726. * @hidden
  24727. * Defines the actions happening during the active mesh stage.
  24728. */
  24729. _this._activeMeshStage = BABYLON.Stage.Create();
  24730. /**
  24731. * @hidden
  24732. * Defines the actions happening during the per camera render target step.
  24733. */
  24734. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24735. /**
  24736. * @hidden
  24737. * Defines the actions happening just before the active camera is drawing.
  24738. */
  24739. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24740. /**
  24741. * @hidden
  24742. * Defines the actions happening just before a rendering group is drawing.
  24743. */
  24744. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24745. /**
  24746. * @hidden
  24747. * Defines the actions happening just before a mesh is drawing.
  24748. */
  24749. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24750. /**
  24751. * @hidden
  24752. * Defines the actions happening just after a mesh has been drawn.
  24753. */
  24754. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24755. /**
  24756. * @hidden
  24757. * Defines the actions happening just after a rendering group has been drawn.
  24758. */
  24759. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24760. /**
  24761. * @hidden
  24762. * Defines the actions happening just after the active camera has been drawn.
  24763. */
  24764. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24765. /**
  24766. * @hidden
  24767. * Defines the actions happening just after rendering all cameras and computing intersections.
  24768. */
  24769. _this._afterRenderStage = BABYLON.Stage.Create();
  24770. /**
  24771. * @hidden
  24772. * Defines the actions happening when a pointer move event happens.
  24773. */
  24774. _this._pointerMoveStage = BABYLON.Stage.Create();
  24775. /**
  24776. * @hidden
  24777. * Defines the actions happening when a pointer down event happens.
  24778. */
  24779. _this._pointerDownStage = BABYLON.Stage.Create();
  24780. /**
  24781. * @hidden
  24782. * Defines the actions happening when a pointer up event happens.
  24783. */
  24784. _this._pointerUpStage = BABYLON.Stage.Create();
  24785. _this._defaultMeshCandidates = {
  24786. data: [],
  24787. length: 0
  24788. };
  24789. _this._defaultSubMeshCandidates = {
  24790. data: [],
  24791. length: 0
  24792. };
  24793. _this._activeMeshesFrozen = false;
  24794. /** @hidden */
  24795. _this._allowPostProcessClearColor = true;
  24796. /**
  24797. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24798. */
  24799. _this.getDeterministicFrameTime = function () {
  24800. return 1000.0 / 60.0; // frame time in ms
  24801. };
  24802. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24803. _this._blockMaterialDirtyMechanism = false;
  24804. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24805. _this._engine.scenes.push(_this);
  24806. _this._uid = null;
  24807. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24808. if (BABYLON.PostProcessManager) {
  24809. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24810. }
  24811. if (BABYLON.Tools.IsWindowObjectExist()) {
  24812. _this.attachControl();
  24813. }
  24814. //collision coordinator initialization. For now legacy per default.
  24815. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24816. // Uniform Buffer
  24817. _this._createUbo();
  24818. // Default Image processing definition
  24819. if (BABYLON.ImageProcessingConfiguration) {
  24820. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24821. }
  24822. _this.setDefaultCandidateProviders();
  24823. return _this;
  24824. }
  24825. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24826. /**
  24827. * Texture used in all pbr material as the reflection texture.
  24828. * As in the majority of the scene they are the same (exception for multi room and so on),
  24829. * this is easier to reference from here than from all the materials.
  24830. */
  24831. get: function () {
  24832. return this._environmentTexture;
  24833. },
  24834. /**
  24835. * Texture used in all pbr material as the reflection texture.
  24836. * As in the majority of the scene they are the same (exception for multi room and so on),
  24837. * this is easier to set here than in all the materials.
  24838. */
  24839. set: function (value) {
  24840. if (this._environmentTexture === value) {
  24841. return;
  24842. }
  24843. this._environmentTexture = value;
  24844. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24845. },
  24846. enumerable: true,
  24847. configurable: true
  24848. });
  24849. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24850. /**
  24851. * Default image processing configuration used either in the rendering
  24852. * Forward main pass or through the imageProcessingPostProcess if present.
  24853. * As in the majority of the scene they are the same (exception for multi camera),
  24854. * this is easier to reference from here than from all the materials and post process.
  24855. *
  24856. * No setter as we it is a shared configuration, you can set the values instead.
  24857. */
  24858. get: function () {
  24859. return this._imageProcessingConfiguration;
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24865. get: function () {
  24866. return this._forceWireframe;
  24867. },
  24868. /**
  24869. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24870. */
  24871. set: function (value) {
  24872. if (this._forceWireframe === value) {
  24873. return;
  24874. }
  24875. this._forceWireframe = value;
  24876. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24882. get: function () {
  24883. return this._forcePointsCloud;
  24884. },
  24885. /**
  24886. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24887. */
  24888. set: function (value) {
  24889. if (this._forcePointsCloud === value) {
  24890. return;
  24891. }
  24892. this._forcePointsCloud = value;
  24893. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24899. /**
  24900. * Gets or sets the animation properties override
  24901. */
  24902. get: function () {
  24903. return this._animationPropertiesOverride;
  24904. },
  24905. set: function (value) {
  24906. this._animationPropertiesOverride = value;
  24907. },
  24908. enumerable: true,
  24909. configurable: true
  24910. });
  24911. Object.defineProperty(Scene.prototype, "onDispose", {
  24912. /** Sets a function to be executed when this scene is disposed. */
  24913. set: function (callback) {
  24914. if (this._onDisposeObserver) {
  24915. this.onDisposeObservable.remove(this._onDisposeObserver);
  24916. }
  24917. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24918. },
  24919. enumerable: true,
  24920. configurable: true
  24921. });
  24922. Object.defineProperty(Scene.prototype, "beforeRender", {
  24923. /** Sets a function to be executed before rendering this scene */
  24924. set: function (callback) {
  24925. if (this._onBeforeRenderObserver) {
  24926. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24927. }
  24928. if (callback) {
  24929. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24930. }
  24931. },
  24932. enumerable: true,
  24933. configurable: true
  24934. });
  24935. Object.defineProperty(Scene.prototype, "afterRender", {
  24936. /** Sets a function to be executed after rendering this scene */
  24937. set: function (callback) {
  24938. if (this._onAfterRenderObserver) {
  24939. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24940. }
  24941. if (callback) {
  24942. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24943. }
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24949. /** Sets a function to be executed before rendering a camera*/
  24950. set: function (callback) {
  24951. if (this._onBeforeCameraRenderObserver) {
  24952. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24953. }
  24954. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24955. },
  24956. enumerable: true,
  24957. configurable: true
  24958. });
  24959. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24960. /** Sets a function to be executed after rendering a camera*/
  24961. set: function (callback) {
  24962. if (this._onAfterCameraRenderObserver) {
  24963. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24964. }
  24965. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24971. /**
  24972. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24973. */
  24974. get: function () {
  24975. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24976. },
  24977. enumerable: true,
  24978. configurable: true
  24979. });
  24980. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24981. get: function () {
  24982. return this._useRightHandedSystem;
  24983. },
  24984. /**
  24985. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24986. */
  24987. set: function (value) {
  24988. if (this._useRightHandedSystem === value) {
  24989. return;
  24990. }
  24991. this._useRightHandedSystem = value;
  24992. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. /**
  24998. * Sets the step Id used by deterministic lock step
  24999. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25000. * @param newStepId defines the step Id
  25001. */
  25002. Scene.prototype.setStepId = function (newStepId) {
  25003. this._currentStepId = newStepId;
  25004. };
  25005. ;
  25006. /**
  25007. * Gets the step Id used by deterministic lock step
  25008. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25009. * @returns the step Id
  25010. */
  25011. Scene.prototype.getStepId = function () {
  25012. return this._currentStepId;
  25013. };
  25014. ;
  25015. /**
  25016. * Gets the internal step used by deterministic lock step
  25017. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25018. * @returns the internal step
  25019. */
  25020. Scene.prototype.getInternalStep = function () {
  25021. return this._currentInternalStep;
  25022. };
  25023. ;
  25024. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25025. get: function () {
  25026. return this._fogEnabled;
  25027. },
  25028. /**
  25029. * Gets or sets a boolean indicating if fog is enabled on this scene
  25030. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25031. */
  25032. set: function (value) {
  25033. if (this._fogEnabled === value) {
  25034. return;
  25035. }
  25036. this._fogEnabled = value;
  25037. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. Object.defineProperty(Scene.prototype, "fogMode", {
  25043. get: function () {
  25044. return this._fogMode;
  25045. },
  25046. /**
  25047. * Gets or sets the fog mode to use
  25048. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25049. */
  25050. set: function (value) {
  25051. if (this._fogMode === value) {
  25052. return;
  25053. }
  25054. this._fogMode = value;
  25055. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25056. },
  25057. enumerable: true,
  25058. configurable: true
  25059. });
  25060. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25061. get: function () {
  25062. return this._shadowsEnabled;
  25063. },
  25064. /**
  25065. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25066. */
  25067. set: function (value) {
  25068. if (this._shadowsEnabled === value) {
  25069. return;
  25070. }
  25071. this._shadowsEnabled = value;
  25072. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25073. },
  25074. enumerable: true,
  25075. configurable: true
  25076. });
  25077. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25078. get: function () {
  25079. return this._lightsEnabled;
  25080. },
  25081. /**
  25082. * Gets or sets a boolean indicating if lights are enabled on this scene
  25083. */
  25084. set: function (value) {
  25085. if (this._lightsEnabled === value) {
  25086. return;
  25087. }
  25088. this._lightsEnabled = value;
  25089. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25090. },
  25091. enumerable: true,
  25092. configurable: true
  25093. });
  25094. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25095. /** The default material used on meshes when no material is affected */
  25096. get: function () {
  25097. if (!this._defaultMaterial) {
  25098. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25099. }
  25100. return this._defaultMaterial;
  25101. },
  25102. /** The default material used on meshes when no material is affected */
  25103. set: function (value) {
  25104. this._defaultMaterial = value;
  25105. },
  25106. enumerable: true,
  25107. configurable: true
  25108. });
  25109. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25110. get: function () {
  25111. return this._texturesEnabled;
  25112. },
  25113. /**
  25114. * Gets or sets a boolean indicating if textures are enabled on this scene
  25115. */
  25116. set: function (value) {
  25117. if (this._texturesEnabled === value) {
  25118. return;
  25119. }
  25120. this._texturesEnabled = value;
  25121. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25122. },
  25123. enumerable: true,
  25124. configurable: true
  25125. });
  25126. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25127. get: function () {
  25128. return this._skeletonsEnabled;
  25129. },
  25130. /**
  25131. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25132. */
  25133. set: function (value) {
  25134. if (this._skeletonsEnabled === value) {
  25135. return;
  25136. }
  25137. this._skeletonsEnabled = value;
  25138. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25139. },
  25140. enumerable: true,
  25141. configurable: true
  25142. });
  25143. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25144. /** @hidden */
  25145. get: function () {
  25146. return this._alternateRendering;
  25147. },
  25148. enumerable: true,
  25149. configurable: true
  25150. });
  25151. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25152. /**
  25153. * Gets the list of frustum planes (built from the active camera)
  25154. */
  25155. get: function () {
  25156. return this._frustumPlanes;
  25157. },
  25158. enumerable: true,
  25159. configurable: true
  25160. });
  25161. /**
  25162. * Registers the transient components if needed.
  25163. */
  25164. Scene.prototype._registerTransientComponents = function () {
  25165. // Register components that have been associated lately to the scene.
  25166. if (this._transientComponents.length > 0) {
  25167. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25168. var component = _a[_i];
  25169. component.register();
  25170. }
  25171. this._transientComponents = [];
  25172. }
  25173. };
  25174. /**
  25175. * @hidden
  25176. * Add a component to the scene.
  25177. * Note that the ccomponent could be registered on th next frame if this is called after
  25178. * the register component stage.
  25179. * @param component Defines the component to add to the scene
  25180. */
  25181. Scene.prototype._addComponent = function (component) {
  25182. this._components.push(component);
  25183. this._transientComponents.push(component);
  25184. var serializableComponent = component;
  25185. if (serializableComponent.addFromContainer) {
  25186. this._serializableComponents.push(serializableComponent);
  25187. }
  25188. };
  25189. /**
  25190. * @hidden
  25191. * Gets a component from the scene.
  25192. * @param name defines the name of the component to retrieve
  25193. * @returns the component or null if not present
  25194. */
  25195. Scene.prototype._getComponent = function (name) {
  25196. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25197. var component = _a[_i];
  25198. if (component.name === name) {
  25199. return component;
  25200. }
  25201. }
  25202. return null;
  25203. };
  25204. /**
  25205. * @hidden
  25206. */
  25207. Scene.prototype._getDefaultMeshCandidates = function () {
  25208. this._defaultMeshCandidates.data = this.meshes;
  25209. this._defaultMeshCandidates.length = this.meshes.length;
  25210. return this._defaultMeshCandidates;
  25211. };
  25212. /**
  25213. * @hidden
  25214. */
  25215. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25216. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25217. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25218. return this._defaultSubMeshCandidates;
  25219. };
  25220. /**
  25221. * Sets the default candidate providers for the scene.
  25222. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25223. * and getCollidingSubMeshCandidates to their default function
  25224. */
  25225. Scene.prototype.setDefaultCandidateProviders = function () {
  25226. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25227. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25228. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25229. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25230. };
  25231. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25232. /**
  25233. * Gets a boolean indicating if collisions are processed on a web worker
  25234. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25235. */
  25236. get: function () {
  25237. return this._workerCollisions;
  25238. },
  25239. set: function (enabled) {
  25240. if (!BABYLON.CollisionCoordinatorLegacy) {
  25241. return;
  25242. }
  25243. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25244. this._workerCollisions = enabled;
  25245. if (this.collisionCoordinator) {
  25246. this.collisionCoordinator.destroy();
  25247. }
  25248. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25249. this.collisionCoordinator.init(this);
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25255. /**
  25256. * Gets the mesh that is currently under the pointer
  25257. */
  25258. get: function () {
  25259. return this._pointerOverMesh;
  25260. },
  25261. enumerable: true,
  25262. configurable: true
  25263. });
  25264. Object.defineProperty(Scene.prototype, "pointerX", {
  25265. /**
  25266. * Gets the current on-screen X position of the pointer
  25267. */
  25268. get: function () {
  25269. return this._pointerX;
  25270. },
  25271. enumerable: true,
  25272. configurable: true
  25273. });
  25274. Object.defineProperty(Scene.prototype, "pointerY", {
  25275. /**
  25276. * Gets the current on-screen Y position of the pointer
  25277. */
  25278. get: function () {
  25279. return this._pointerY;
  25280. },
  25281. enumerable: true,
  25282. configurable: true
  25283. });
  25284. /**
  25285. * Gets the cached material (ie. the latest rendered one)
  25286. * @returns the cached material
  25287. */
  25288. Scene.prototype.getCachedMaterial = function () {
  25289. return this._cachedMaterial;
  25290. };
  25291. /**
  25292. * Gets the cached effect (ie. the latest rendered one)
  25293. * @returns the cached effect
  25294. */
  25295. Scene.prototype.getCachedEffect = function () {
  25296. return this._cachedEffect;
  25297. };
  25298. /**
  25299. * Gets the cached visibility state (ie. the latest rendered one)
  25300. * @returns the cached visibility state
  25301. */
  25302. Scene.prototype.getCachedVisibility = function () {
  25303. return this._cachedVisibility;
  25304. };
  25305. /**
  25306. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25307. * @param material defines the current material
  25308. * @param effect defines the current effect
  25309. * @param visibility defines the current visibility state
  25310. * @returns true if one parameter is not cached
  25311. */
  25312. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25313. if (visibility === void 0) { visibility = 1; }
  25314. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25315. };
  25316. /**
  25317. * Gets the engine associated with the scene
  25318. * @returns an Engine
  25319. */
  25320. Scene.prototype.getEngine = function () {
  25321. return this._engine;
  25322. };
  25323. /**
  25324. * Gets the total number of vertices rendered per frame
  25325. * @returns the total number of vertices rendered per frame
  25326. */
  25327. Scene.prototype.getTotalVertices = function () {
  25328. return this._totalVertices.current;
  25329. };
  25330. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25331. /**
  25332. * Gets the performance counter for total vertices
  25333. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25334. */
  25335. get: function () {
  25336. return this._totalVertices;
  25337. },
  25338. enumerable: true,
  25339. configurable: true
  25340. });
  25341. /**
  25342. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25343. * @returns the total number of active indices rendered per frame
  25344. */
  25345. Scene.prototype.getActiveIndices = function () {
  25346. return this._activeIndices.current;
  25347. };
  25348. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25349. /**
  25350. * Gets the performance counter for active indices
  25351. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25352. */
  25353. get: function () {
  25354. return this._activeIndices;
  25355. },
  25356. enumerable: true,
  25357. configurable: true
  25358. });
  25359. /**
  25360. * Gets the total number of active particles rendered per frame
  25361. * @returns the total number of active particles rendered per frame
  25362. */
  25363. Scene.prototype.getActiveParticles = function () {
  25364. return this._activeParticles.current;
  25365. };
  25366. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25367. /**
  25368. * Gets the performance counter for active particles
  25369. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25370. */
  25371. get: function () {
  25372. return this._activeParticles;
  25373. },
  25374. enumerable: true,
  25375. configurable: true
  25376. });
  25377. /**
  25378. * Gets the total number of active bones rendered per frame
  25379. * @returns the total number of active bones rendered per frame
  25380. */
  25381. Scene.prototype.getActiveBones = function () {
  25382. return this._activeBones.current;
  25383. };
  25384. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25385. /**
  25386. * Gets the performance counter for active bones
  25387. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25388. */
  25389. get: function () {
  25390. return this._activeBones;
  25391. },
  25392. enumerable: true,
  25393. configurable: true
  25394. });
  25395. /** @hidden */
  25396. Scene.prototype.getInterFramePerfCounter = function () {
  25397. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25398. return 0;
  25399. };
  25400. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25401. /** @hidden */
  25402. get: function () {
  25403. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25404. return null;
  25405. },
  25406. enumerable: true,
  25407. configurable: true
  25408. });
  25409. /** @hidden */
  25410. Scene.prototype.getLastFrameDuration = function () {
  25411. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25412. return 0;
  25413. };
  25414. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25415. /** @hidden */
  25416. get: function () {
  25417. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25418. return null;
  25419. },
  25420. enumerable: true,
  25421. configurable: true
  25422. });
  25423. /** @hidden */
  25424. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25425. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25426. return 0;
  25427. };
  25428. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25429. /** @hidden */
  25430. get: function () {
  25431. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25432. return null;
  25433. },
  25434. enumerable: true,
  25435. configurable: true
  25436. });
  25437. /**
  25438. * Gets the array of active meshes
  25439. * @returns an array of AbstractMesh
  25440. */
  25441. Scene.prototype.getActiveMeshes = function () {
  25442. return this._activeMeshes;
  25443. };
  25444. /** @hidden */
  25445. Scene.prototype.getRenderTargetsDuration = function () {
  25446. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25447. return 0;
  25448. };
  25449. /** @hidden */
  25450. Scene.prototype.getRenderDuration = function () {
  25451. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25452. return 0;
  25453. };
  25454. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25455. /** @hidden */
  25456. get: function () {
  25457. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25458. return null;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. /** @hidden */
  25464. Scene.prototype.getParticlesDuration = function () {
  25465. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25466. return 0;
  25467. };
  25468. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25469. /** @hidden */
  25470. get: function () {
  25471. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25472. return null;
  25473. },
  25474. enumerable: true,
  25475. configurable: true
  25476. });
  25477. /** @hidden */
  25478. Scene.prototype.getSpritesDuration = function () {
  25479. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25480. return 0;
  25481. };
  25482. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25483. /** @hidden */
  25484. get: function () {
  25485. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25486. return null;
  25487. },
  25488. enumerable: true,
  25489. configurable: true
  25490. });
  25491. /**
  25492. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25493. * @returns a number
  25494. */
  25495. Scene.prototype.getAnimationRatio = function () {
  25496. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25497. };
  25498. /**
  25499. * Gets an unique Id for the current render phase
  25500. * @returns a number
  25501. */
  25502. Scene.prototype.getRenderId = function () {
  25503. return this._renderId;
  25504. };
  25505. /**
  25506. * Gets an unique Id for the current frame
  25507. * @returns a number
  25508. */
  25509. Scene.prototype.getFrameId = function () {
  25510. return this._frameId;
  25511. };
  25512. /** Call this function if you want to manually increment the render Id*/
  25513. Scene.prototype.incrementRenderId = function () {
  25514. this._renderId++;
  25515. };
  25516. Scene.prototype._updatePointerPosition = function (evt) {
  25517. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25518. if (!canvasRect) {
  25519. return;
  25520. }
  25521. this._pointerX = evt.clientX - canvasRect.left;
  25522. this._pointerY = evt.clientY - canvasRect.top;
  25523. this._unTranslatedPointerX = this._pointerX;
  25524. this._unTranslatedPointerY = this._pointerY;
  25525. };
  25526. Scene.prototype._createUbo = function () {
  25527. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25528. this._sceneUbo.addUniform("viewProjection", 16);
  25529. this._sceneUbo.addUniform("view", 16);
  25530. };
  25531. Scene.prototype._createAlternateUbo = function () {
  25532. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25533. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25534. this._alternateSceneUbo.addUniform("view", 16);
  25535. };
  25536. // Pointers handling
  25537. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25538. if (pointerInfo.pickInfo) {
  25539. if (!pointerInfo.pickInfo.ray) {
  25540. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25541. }
  25542. }
  25543. };
  25544. /**
  25545. * Use this method to simulate a pointer move on a mesh
  25546. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25547. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25548. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25549. * @returns the current scene
  25550. */
  25551. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25552. var evt = new PointerEvent("pointermove", pointerEventInit);
  25553. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25554. return this;
  25555. }
  25556. return this._processPointerMove(pickResult, evt);
  25557. };
  25558. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25559. var canvas = this._engine.getRenderingCanvas();
  25560. if (!canvas) {
  25561. return this;
  25562. }
  25563. // Restore pointer
  25564. canvas.style.cursor = this.defaultCursor;
  25565. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25566. if (isMeshPicked) {
  25567. this.setPointerOverMesh(pickResult.pickedMesh);
  25568. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25569. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25570. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25571. }
  25572. else {
  25573. canvas.style.cursor = this.hoverCursor;
  25574. }
  25575. }
  25576. }
  25577. else {
  25578. this.setPointerOverMesh(null);
  25579. }
  25580. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25581. var step = _a[_i];
  25582. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25583. }
  25584. if (pickResult) {
  25585. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25586. if (this.onPointerMove) {
  25587. this.onPointerMove(evt, pickResult, type);
  25588. }
  25589. if (this.onPointerObservable.hasObservers()) {
  25590. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25591. this._setRayOnPointerInfo(pi);
  25592. this.onPointerObservable.notifyObservers(pi, type);
  25593. }
  25594. }
  25595. return this;
  25596. };
  25597. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25598. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25599. if (pickResult) {
  25600. pi.ray = pickResult.ray;
  25601. }
  25602. this.onPrePointerObservable.notifyObservers(pi, type);
  25603. if (pi.skipOnPointerObservable) {
  25604. return true;
  25605. }
  25606. else {
  25607. return false;
  25608. }
  25609. };
  25610. /**
  25611. * Use this method to simulate a pointer down on a mesh
  25612. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25613. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25614. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25615. * @returns the current scene
  25616. */
  25617. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25618. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25619. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25620. return this;
  25621. }
  25622. return this._processPointerDown(pickResult, evt);
  25623. };
  25624. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25625. var _this = this;
  25626. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25627. this._pickedDownMesh = pickResult.pickedMesh;
  25628. var actionManager = pickResult.pickedMesh.actionManager;
  25629. if (actionManager) {
  25630. if (actionManager.hasPickTriggers) {
  25631. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25632. switch (evt.button) {
  25633. case 0:
  25634. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25635. break;
  25636. case 1:
  25637. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25638. break;
  25639. case 2:
  25640. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25641. break;
  25642. }
  25643. }
  25644. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25645. window.setTimeout(function () {
  25646. 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);
  25647. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25648. if (_this._totalPointersPressed !== 0 &&
  25649. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25650. !_this._isPointerSwiping()) {
  25651. _this._startingPointerTime = 0;
  25652. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25653. }
  25654. }
  25655. }, Scene.LongPressDelay);
  25656. }
  25657. }
  25658. }
  25659. else {
  25660. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25661. var step = _a[_i];
  25662. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25663. }
  25664. }
  25665. if (pickResult) {
  25666. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25667. if (this.onPointerDown) {
  25668. this.onPointerDown(evt, pickResult, type);
  25669. }
  25670. if (this.onPointerObservable.hasObservers()) {
  25671. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25672. this._setRayOnPointerInfo(pi);
  25673. this.onPointerObservable.notifyObservers(pi, type);
  25674. }
  25675. }
  25676. return this;
  25677. };
  25678. /**
  25679. * Use this method to simulate a pointer up on a mesh
  25680. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25681. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25682. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25683. * @returns the current scene
  25684. */
  25685. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25686. var evt = new PointerEvent("pointerup", pointerEventInit);
  25687. var clickInfo = new ClickInfo();
  25688. clickInfo.singleClick = true;
  25689. clickInfo.ignore = true;
  25690. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25691. return this;
  25692. }
  25693. return this._processPointerUp(pickResult, evt, clickInfo);
  25694. };
  25695. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25696. if (pickResult && pickResult && pickResult.pickedMesh) {
  25697. this._pickedUpMesh = pickResult.pickedMesh;
  25698. if (this._pickedDownMesh === this._pickedUpMesh) {
  25699. if (this.onPointerPick) {
  25700. this.onPointerPick(evt, pickResult);
  25701. }
  25702. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25703. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25704. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25705. this._setRayOnPointerInfo(pi);
  25706. this.onPointerObservable.notifyObservers(pi, type_1);
  25707. }
  25708. }
  25709. if (pickResult.pickedMesh.actionManager) {
  25710. if (clickInfo.ignore) {
  25711. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25712. }
  25713. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25714. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25715. }
  25716. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25718. }
  25719. }
  25720. }
  25721. else {
  25722. if (!clickInfo.ignore) {
  25723. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25724. var step = _a[_i];
  25725. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25726. }
  25727. }
  25728. }
  25729. if (this._pickedDownMesh &&
  25730. this._pickedDownMesh.actionManager &&
  25731. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25732. this._pickedDownMesh !== this._pickedUpMesh) {
  25733. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25734. }
  25735. var type = BABYLON.PointerEventTypes.POINTERUP;
  25736. if (this.onPointerObservable.hasObservers()) {
  25737. if (!clickInfo.ignore) {
  25738. if (!clickInfo.hasSwiped) {
  25739. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25740. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25741. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25742. this._setRayOnPointerInfo(pi);
  25743. this.onPointerObservable.notifyObservers(pi, type_2);
  25744. }
  25745. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25746. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25747. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25748. this._setRayOnPointerInfo(pi);
  25749. this.onPointerObservable.notifyObservers(pi, type_3);
  25750. }
  25751. }
  25752. }
  25753. else {
  25754. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25755. this._setRayOnPointerInfo(pi);
  25756. this.onPointerObservable.notifyObservers(pi, type);
  25757. }
  25758. }
  25759. if (this.onPointerUp) {
  25760. this.onPointerUp(evt, pickResult, type);
  25761. }
  25762. return this;
  25763. };
  25764. /**
  25765. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25766. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25767. * @returns true if the pointer was captured
  25768. */
  25769. Scene.prototype.isPointerCaptured = function (pointerId) {
  25770. if (pointerId === void 0) { pointerId = 0; }
  25771. return this._pointerCaptures[pointerId];
  25772. };
  25773. /** @hidden */
  25774. Scene.prototype._isPointerSwiping = function () {
  25775. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25776. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25777. };
  25778. /**
  25779. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25780. * @param attachUp defines if you want to attach events to pointerup
  25781. * @param attachDown defines if you want to attach events to pointerdown
  25782. * @param attachMove defines if you want to attach events to pointermove
  25783. */
  25784. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25785. var _this = this;
  25786. if (attachUp === void 0) { attachUp = true; }
  25787. if (attachDown === void 0) { attachDown = true; }
  25788. if (attachMove === void 0) { attachMove = true; }
  25789. this._initActionManager = function (act, clickInfo) {
  25790. if (!_this._meshPickProceed) {
  25791. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25792. _this._currentPickResult = pickResult;
  25793. if (pickResult) {
  25794. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25795. }
  25796. _this._meshPickProceed = true;
  25797. }
  25798. return act;
  25799. };
  25800. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25801. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25802. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25803. btn !== _this._previousButtonPressed) {
  25804. _this._doubleClickOccured = false;
  25805. clickInfo.singleClick = true;
  25806. clickInfo.ignore = false;
  25807. cb(clickInfo, _this._currentPickResult);
  25808. }
  25809. };
  25810. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25811. var clickInfo = new ClickInfo();
  25812. _this._currentPickResult = null;
  25813. var act = null;
  25814. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25815. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25816. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25817. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25818. act = _this._initActionManager(act, clickInfo);
  25819. if (act)
  25820. checkPicking = act.hasPickTriggers;
  25821. }
  25822. if (checkPicking) {
  25823. var btn = evt.button;
  25824. clickInfo.hasSwiped = _this._isPointerSwiping();
  25825. if (!clickInfo.hasSwiped) {
  25826. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25827. if (!checkSingleClickImmediately) {
  25828. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25829. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25830. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25831. act = _this._initActionManager(act, clickInfo);
  25832. if (act)
  25833. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25834. }
  25835. }
  25836. if (checkSingleClickImmediately) {
  25837. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25838. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25839. btn !== _this._previousButtonPressed) {
  25840. clickInfo.singleClick = true;
  25841. cb(clickInfo, _this._currentPickResult);
  25842. }
  25843. }
  25844. // at least one double click is required to be check and exclusive double click is enabled
  25845. else {
  25846. // wait that no double click has been raised during the double click delay
  25847. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25848. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25849. }
  25850. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25851. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25852. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25853. act = _this._initActionManager(act, clickInfo);
  25854. if (act)
  25855. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25856. }
  25857. if (checkDoubleClick) {
  25858. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25859. if (btn === _this._previousButtonPressed &&
  25860. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25861. !_this._doubleClickOccured) {
  25862. // pointer has not moved for 2 clicks, it's a double click
  25863. if (!clickInfo.hasSwiped &&
  25864. !_this._isPointerSwiping()) {
  25865. _this._previousStartingPointerTime = 0;
  25866. _this._doubleClickOccured = true;
  25867. clickInfo.doubleClick = true;
  25868. clickInfo.ignore = false;
  25869. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25870. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25871. }
  25872. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25873. cb(clickInfo, _this._currentPickResult);
  25874. }
  25875. // if the two successive clicks are too far, it's just two simple clicks
  25876. else {
  25877. _this._doubleClickOccured = false;
  25878. _this._previousStartingPointerTime = _this._startingPointerTime;
  25879. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25880. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25881. _this._previousButtonPressed = btn;
  25882. if (Scene.ExclusiveDoubleClickMode) {
  25883. if (_this._previousDelayedSimpleClickTimeout) {
  25884. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25885. }
  25886. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25887. cb(clickInfo, _this._previousPickResult);
  25888. }
  25889. else {
  25890. cb(clickInfo, _this._currentPickResult);
  25891. }
  25892. }
  25893. }
  25894. // just the first click of the double has been raised
  25895. else {
  25896. _this._doubleClickOccured = false;
  25897. _this._previousStartingPointerTime = _this._startingPointerTime;
  25898. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25899. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25900. _this._previousButtonPressed = btn;
  25901. }
  25902. }
  25903. }
  25904. }
  25905. clickInfo.ignore = true;
  25906. cb(clickInfo, _this._currentPickResult);
  25907. };
  25908. this._onPointerMove = function (evt) {
  25909. _this._updatePointerPosition(evt);
  25910. // PreObservable support
  25911. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25912. return;
  25913. }
  25914. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25915. return;
  25916. }
  25917. if (!_this.pointerMovePredicate) {
  25918. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25919. }
  25920. // Meshes
  25921. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25922. _this._processPointerMove(pickResult, evt);
  25923. };
  25924. this._onPointerDown = function (evt) {
  25925. _this._totalPointersPressed++;
  25926. _this._pickedDownMesh = null;
  25927. _this._meshPickProceed = false;
  25928. _this._updatePointerPosition(evt);
  25929. if (_this.preventDefaultOnPointerDown && canvas) {
  25930. evt.preventDefault();
  25931. canvas.focus();
  25932. }
  25933. // PreObservable support
  25934. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25935. return;
  25936. }
  25937. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25938. return;
  25939. }
  25940. _this._pointerCaptures[evt.pointerId] = true;
  25941. _this._startingPointerPosition.x = _this._pointerX;
  25942. _this._startingPointerPosition.y = _this._pointerY;
  25943. _this._startingPointerTime = Date.now();
  25944. if (!_this.pointerDownPredicate) {
  25945. _this.pointerDownPredicate = function (mesh) {
  25946. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25947. };
  25948. }
  25949. // Meshes
  25950. _this._pickedDownMesh = null;
  25951. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25952. _this._processPointerDown(pickResult, evt);
  25953. };
  25954. this._onPointerUp = function (evt) {
  25955. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25956. return; // So we need to test it the pointer down was pressed before.
  25957. }
  25958. _this._totalPointersPressed--;
  25959. _this._pickedUpMesh = null;
  25960. _this._meshPickProceed = false;
  25961. _this._updatePointerPosition(evt);
  25962. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25963. // PreObservable support
  25964. if (_this.onPrePointerObservable.hasObservers()) {
  25965. if (!clickInfo.ignore) {
  25966. if (!clickInfo.hasSwiped) {
  25967. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25968. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25969. return;
  25970. }
  25971. }
  25972. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25973. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25974. return;
  25975. }
  25976. }
  25977. }
  25978. }
  25979. else {
  25980. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25981. return;
  25982. }
  25983. }
  25984. }
  25985. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25986. return;
  25987. }
  25988. _this._pointerCaptures[evt.pointerId] = false;
  25989. if (!_this.pointerUpPredicate) {
  25990. _this.pointerUpPredicate = function (mesh) {
  25991. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25992. };
  25993. }
  25994. // Meshes
  25995. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25996. _this._initActionManager(null, clickInfo);
  25997. }
  25998. if (!pickResult) {
  25999. pickResult = _this._currentPickResult;
  26000. }
  26001. _this._processPointerUp(pickResult, evt, clickInfo);
  26002. _this._previousPickResult = _this._currentPickResult;
  26003. });
  26004. };
  26005. this._onKeyDown = function (evt) {
  26006. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26007. if (_this.onPreKeyboardObservable.hasObservers()) {
  26008. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26009. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26010. if (pi.skipOnPointerObservable) {
  26011. return;
  26012. }
  26013. }
  26014. if (_this.onKeyboardObservable.hasObservers()) {
  26015. var pi = new BABYLON.KeyboardInfo(type, evt);
  26016. _this.onKeyboardObservable.notifyObservers(pi, type);
  26017. }
  26018. if (_this.actionManager) {
  26019. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26020. }
  26021. };
  26022. this._onKeyUp = function (evt) {
  26023. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26024. if (_this.onPreKeyboardObservable.hasObservers()) {
  26025. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26026. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26027. if (pi.skipOnPointerObservable) {
  26028. return;
  26029. }
  26030. }
  26031. if (_this.onKeyboardObservable.hasObservers()) {
  26032. var pi = new BABYLON.KeyboardInfo(type, evt);
  26033. _this.onKeyboardObservable.notifyObservers(pi, type);
  26034. }
  26035. if (_this.actionManager) {
  26036. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26037. }
  26038. };
  26039. var engine = this.getEngine();
  26040. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26041. if (!canvas) {
  26042. return;
  26043. }
  26044. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26045. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26046. });
  26047. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26048. if (!canvas) {
  26049. return;
  26050. }
  26051. canvas.removeEventListener("keydown", _this._onKeyDown);
  26052. canvas.removeEventListener("keyup", _this._onKeyUp);
  26053. });
  26054. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26055. var canvas = this._engine.getRenderingCanvas();
  26056. if (!canvas) {
  26057. return;
  26058. }
  26059. if (attachMove) {
  26060. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26061. // Wheel
  26062. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26063. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26064. }
  26065. if (attachDown) {
  26066. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26067. }
  26068. if (attachUp) {
  26069. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26070. }
  26071. canvas.tabIndex = 1;
  26072. };
  26073. /** Detaches all event handlers*/
  26074. Scene.prototype.detachControl = function () {
  26075. var engine = this.getEngine();
  26076. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26077. var canvas = engine.getRenderingCanvas();
  26078. if (!canvas) {
  26079. return;
  26080. }
  26081. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26082. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26083. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26084. if (this._onCanvasBlurObserver) {
  26085. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26086. }
  26087. if (this._onCanvasFocusObserver) {
  26088. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26089. }
  26090. // Wheel
  26091. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26092. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26093. // Keyboard
  26094. canvas.removeEventListener("keydown", this._onKeyDown);
  26095. canvas.removeEventListener("keyup", this._onKeyUp);
  26096. // Observables
  26097. this.onKeyboardObservable.clear();
  26098. this.onPreKeyboardObservable.clear();
  26099. this.onPointerObservable.clear();
  26100. this.onPrePointerObservable.clear();
  26101. };
  26102. /**
  26103. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26104. * Delay loaded resources are not taking in account
  26105. * @return true if all required resources are ready
  26106. */
  26107. Scene.prototype.isReady = function () {
  26108. if (this._isDisposed) {
  26109. return false;
  26110. }
  26111. if (this._pendingData.length > 0) {
  26112. return false;
  26113. }
  26114. var index;
  26115. var engine = this.getEngine();
  26116. // Geometries
  26117. for (index = 0; index < this.geometries.length; index++) {
  26118. var geometry = this.geometries[index];
  26119. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26120. return false;
  26121. }
  26122. }
  26123. // Meshes
  26124. for (index = 0; index < this.meshes.length; index++) {
  26125. var mesh = this.meshes[index];
  26126. if (!mesh.isEnabled()) {
  26127. continue;
  26128. }
  26129. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26130. continue;
  26131. }
  26132. if (!mesh.isReady(true)) {
  26133. return false;
  26134. }
  26135. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26136. // Is Ready For Mesh
  26137. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26138. var step = _a[_i];
  26139. if (!step.action(mesh, hardwareInstancedRendering)) {
  26140. return false;
  26141. }
  26142. }
  26143. }
  26144. // Post-processes
  26145. if (this.activeCameras && this.activeCameras.length > 0) {
  26146. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26147. var camera = _c[_b];
  26148. if (!camera.isReady(true)) {
  26149. return false;
  26150. }
  26151. }
  26152. }
  26153. else if (this.activeCamera) {
  26154. if (!this.activeCamera.isReady(true)) {
  26155. return false;
  26156. }
  26157. }
  26158. // Particles
  26159. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26160. var particleSystem = _e[_d];
  26161. if (!particleSystem.isReady()) {
  26162. return false;
  26163. }
  26164. }
  26165. return true;
  26166. };
  26167. /** Resets all cached information relative to material (including effect and visibility) */
  26168. Scene.prototype.resetCachedMaterial = function () {
  26169. this._cachedMaterial = null;
  26170. this._cachedEffect = null;
  26171. this._cachedVisibility = null;
  26172. };
  26173. /**
  26174. * Registers a function to be called before every frame render
  26175. * @param func defines the function to register
  26176. */
  26177. Scene.prototype.registerBeforeRender = function (func) {
  26178. this.onBeforeRenderObservable.add(func);
  26179. };
  26180. /**
  26181. * Unregisters a function called before every frame render
  26182. * @param func defines the function to unregister
  26183. */
  26184. Scene.prototype.unregisterBeforeRender = function (func) {
  26185. this.onBeforeRenderObservable.removeCallback(func);
  26186. };
  26187. /**
  26188. * Registers a function to be called after every frame render
  26189. * @param func defines the function to register
  26190. */
  26191. Scene.prototype.registerAfterRender = function (func) {
  26192. this.onAfterRenderObservable.add(func);
  26193. };
  26194. /**
  26195. * Unregisters a function called after every frame render
  26196. * @param func defines the function to unregister
  26197. */
  26198. Scene.prototype.unregisterAfterRender = function (func) {
  26199. this.onAfterRenderObservable.removeCallback(func);
  26200. };
  26201. Scene.prototype._executeOnceBeforeRender = function (func) {
  26202. var _this = this;
  26203. var execFunc = function () {
  26204. func();
  26205. setTimeout(function () {
  26206. _this.unregisterBeforeRender(execFunc);
  26207. });
  26208. };
  26209. this.registerBeforeRender(execFunc);
  26210. };
  26211. /**
  26212. * The provided function will run before render once and will be disposed afterwards.
  26213. * A timeout delay can be provided so that the function will be executed in N ms.
  26214. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26215. * @param func The function to be executed.
  26216. * @param timeout optional delay in ms
  26217. */
  26218. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26219. var _this = this;
  26220. if (timeout !== undefined) {
  26221. setTimeout(function () {
  26222. _this._executeOnceBeforeRender(func);
  26223. }, timeout);
  26224. }
  26225. else {
  26226. this._executeOnceBeforeRender(func);
  26227. }
  26228. };
  26229. /** @hidden */
  26230. Scene.prototype._addPendingData = function (data) {
  26231. this._pendingData.push(data);
  26232. };
  26233. /** @hidden */
  26234. Scene.prototype._removePendingData = function (data) {
  26235. var wasLoading = this.isLoading;
  26236. var index = this._pendingData.indexOf(data);
  26237. if (index !== -1) {
  26238. this._pendingData.splice(index, 1);
  26239. }
  26240. if (wasLoading && !this.isLoading) {
  26241. this.onDataLoadedObservable.notifyObservers(this);
  26242. }
  26243. };
  26244. /**
  26245. * Returns the number of items waiting to be loaded
  26246. * @returns the number of items waiting to be loaded
  26247. */
  26248. Scene.prototype.getWaitingItemsCount = function () {
  26249. return this._pendingData.length;
  26250. };
  26251. Object.defineProperty(Scene.prototype, "isLoading", {
  26252. /**
  26253. * Returns a boolean indicating if the scene is still loading data
  26254. */
  26255. get: function () {
  26256. return this._pendingData.length > 0;
  26257. },
  26258. enumerable: true,
  26259. configurable: true
  26260. });
  26261. /**
  26262. * Registers a function to be executed when the scene is ready
  26263. * @param {Function} func - the function to be executed
  26264. */
  26265. Scene.prototype.executeWhenReady = function (func) {
  26266. var _this = this;
  26267. this.onReadyObservable.add(func);
  26268. if (this._executeWhenReadyTimeoutId !== -1) {
  26269. return;
  26270. }
  26271. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26272. _this._checkIsReady();
  26273. }, 150);
  26274. };
  26275. /**
  26276. * Returns a promise that resolves when the scene is ready
  26277. * @returns A promise that resolves when the scene is ready
  26278. */
  26279. Scene.prototype.whenReadyAsync = function () {
  26280. var _this = this;
  26281. return new Promise(function (resolve) {
  26282. _this.executeWhenReady(function () {
  26283. resolve();
  26284. });
  26285. });
  26286. };
  26287. /** @hidden */
  26288. Scene.prototype._checkIsReady = function () {
  26289. var _this = this;
  26290. this._registerTransientComponents();
  26291. if (this.isReady()) {
  26292. this.onReadyObservable.notifyObservers(this);
  26293. this.onReadyObservable.clear();
  26294. this._executeWhenReadyTimeoutId = -1;
  26295. return;
  26296. }
  26297. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26298. _this._checkIsReady();
  26299. }, 150);
  26300. };
  26301. // Animations
  26302. /**
  26303. * Will start the animation sequence of a given target
  26304. * @param target defines the target
  26305. * @param from defines from which frame should animation start
  26306. * @param to defines until which frame should animation run.
  26307. * @param weight defines the weight to apply to the animation (1.0 by default)
  26308. * @param loop defines if the animation loops
  26309. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26310. * @param onAnimationEnd defines the function to be executed when the animation ends
  26311. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26312. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26313. * @returns the animatable object created for this animation
  26314. */
  26315. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26316. if (weight === void 0) { weight = 1.0; }
  26317. if (speedRatio === void 0) { speedRatio = 1.0; }
  26318. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26319. returnedAnimatable.weight = weight;
  26320. return returnedAnimatable;
  26321. };
  26322. /**
  26323. * Will start the animation sequence of a given target
  26324. * @param target defines the target
  26325. * @param from defines from which frame should animation start
  26326. * @param to defines until which frame should animation run.
  26327. * @param loop defines if the animation loops
  26328. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26329. * @param onAnimationEnd defines the function to be executed when the animation ends
  26330. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26331. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26332. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26333. * @returns the animatable object created for this animation
  26334. */
  26335. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26336. if (speedRatio === void 0) { speedRatio = 1.0; }
  26337. if (stopCurrent === void 0) { stopCurrent = true; }
  26338. if (from > to && speedRatio > 0) {
  26339. speedRatio *= -1;
  26340. }
  26341. if (stopCurrent) {
  26342. this.stopAnimation(target, undefined, targetMask);
  26343. }
  26344. if (!animatable) {
  26345. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26346. }
  26347. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26348. // Local animations
  26349. if (target.animations && shouldRunTargetAnimations) {
  26350. animatable.appendAnimations(target, target.animations);
  26351. }
  26352. // Children animations
  26353. if (target.getAnimatables) {
  26354. var animatables = target.getAnimatables();
  26355. for (var index = 0; index < animatables.length; index++) {
  26356. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26357. }
  26358. }
  26359. animatable.reset();
  26360. return animatable;
  26361. };
  26362. /**
  26363. * Begin a new animation on a given node
  26364. * @param target defines the target where the animation will take place
  26365. * @param animations defines the list of animations to start
  26366. * @param from defines the initial value
  26367. * @param to defines the final value
  26368. * @param loop defines if you want animation to loop (off by default)
  26369. * @param speedRatio defines the speed ratio to apply to all animations
  26370. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26371. * @returns the list of created animatables
  26372. */
  26373. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26374. if (speedRatio === undefined) {
  26375. speedRatio = 1.0;
  26376. }
  26377. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26378. return animatable;
  26379. };
  26380. /**
  26381. * Begin a new animation on a given node and its hierarchy
  26382. * @param target defines the root node where the animation will take place
  26383. * @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.
  26384. * @param animations defines the list of animations to start
  26385. * @param from defines the initial value
  26386. * @param to defines the final value
  26387. * @param loop defines if you want animation to loop (off by default)
  26388. * @param speedRatio defines the speed ratio to apply to all animations
  26389. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26390. * @returns the list of animatables created for all nodes
  26391. */
  26392. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26393. var children = target.getDescendants(directDescendantsOnly);
  26394. var result = [];
  26395. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26396. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26397. var child = children_1[_i];
  26398. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26399. }
  26400. return result;
  26401. };
  26402. /**
  26403. * Gets the animatable associated with a specific target
  26404. * @param target defines the target of the animatable
  26405. * @returns the required animatable if found
  26406. */
  26407. Scene.prototype.getAnimatableByTarget = function (target) {
  26408. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26409. if (this._activeAnimatables[index].target === target) {
  26410. return this._activeAnimatables[index];
  26411. }
  26412. }
  26413. return null;
  26414. };
  26415. /**
  26416. * Gets all animatables associated with a given target
  26417. * @param target defines the target to look animatables for
  26418. * @returns an array of Animatables
  26419. */
  26420. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26421. var result = [];
  26422. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26423. if (this._activeAnimatables[index].target === target) {
  26424. result.push(this._activeAnimatables[index]);
  26425. }
  26426. }
  26427. return result;
  26428. };
  26429. Object.defineProperty(Scene.prototype, "animatables", {
  26430. /**
  26431. * Gets all animatable attached to the scene
  26432. */
  26433. get: function () {
  26434. return this._activeAnimatables;
  26435. },
  26436. enumerable: true,
  26437. configurable: true
  26438. });
  26439. /**
  26440. * Will stop the animation of the given target
  26441. * @param target - the target
  26442. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26443. * @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)
  26444. */
  26445. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26446. var animatables = this.getAllAnimatablesByTarget(target);
  26447. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26448. var animatable = animatables_1[_i];
  26449. animatable.stop(animationName, targetMask);
  26450. }
  26451. };
  26452. /**
  26453. * Stops and removes all animations that have been applied to the scene
  26454. */
  26455. Scene.prototype.stopAllAnimations = function () {
  26456. if (this._activeAnimatables) {
  26457. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26458. this._activeAnimatables[i].stop();
  26459. }
  26460. this._activeAnimatables = [];
  26461. }
  26462. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26463. var group = _a[_i];
  26464. group.stop();
  26465. }
  26466. };
  26467. Scene.prototype._animate = function () {
  26468. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26469. return;
  26470. }
  26471. // Getting time
  26472. var now = BABYLON.Tools.Now;
  26473. if (!this._animationTimeLast) {
  26474. if (this._pendingData.length > 0) {
  26475. return;
  26476. }
  26477. this._animationTimeLast = now;
  26478. }
  26479. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26480. this._animationTime += deltaTime;
  26481. this._animationTimeLast = now;
  26482. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26483. this._activeAnimatables[index]._animate(this._animationTime);
  26484. }
  26485. // Late animation bindings
  26486. this._processLateAnimationBindings();
  26487. };
  26488. /** @hidden */
  26489. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26490. var target = runtimeAnimation.target;
  26491. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26492. if (!target._lateAnimationHolders) {
  26493. target._lateAnimationHolders = {};
  26494. }
  26495. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26496. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26497. totalWeight: 0,
  26498. animations: [],
  26499. originalValue: originalValue
  26500. };
  26501. }
  26502. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26503. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26504. };
  26505. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26506. var normalizer = 1.0;
  26507. var finalPosition = BABYLON.Tmp.Vector3[0];
  26508. var finalScaling = BABYLON.Tmp.Vector3[1];
  26509. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26510. var startIndex = 0;
  26511. var originalAnimation = holder.animations[0];
  26512. var originalValue = holder.originalValue;
  26513. var scale = 1;
  26514. if (holder.totalWeight < 1.0) {
  26515. // We need to mix the original value in
  26516. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26517. scale = 1.0 - holder.totalWeight;
  26518. }
  26519. else {
  26520. startIndex = 1;
  26521. // We need to normalize the weights
  26522. normalizer = holder.totalWeight;
  26523. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26524. scale = originalAnimation.weight / normalizer;
  26525. if (scale == 1) {
  26526. return originalAnimation.currentValue;
  26527. }
  26528. }
  26529. finalScaling.scaleInPlace(scale);
  26530. finalPosition.scaleInPlace(scale);
  26531. finalQuaternion.scaleInPlace(scale);
  26532. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26533. var runtimeAnimation = holder.animations[animIndex];
  26534. var scale = runtimeAnimation.weight / normalizer;
  26535. var currentPosition = BABYLON.Tmp.Vector3[2];
  26536. var currentScaling = BABYLON.Tmp.Vector3[3];
  26537. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26538. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26539. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26540. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26541. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26542. }
  26543. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26544. return originalAnimation._workValue;
  26545. };
  26546. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26547. var originalAnimation = holder.animations[0];
  26548. var originalValue = holder.originalValue;
  26549. if (holder.animations.length === 1) {
  26550. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26551. return refQuaternion;
  26552. }
  26553. var normalizer = 1.0;
  26554. var quaternions;
  26555. var weights;
  26556. if (holder.totalWeight < 1.0) {
  26557. var scale = 1.0 - holder.totalWeight;
  26558. quaternions = [];
  26559. weights = [];
  26560. quaternions.push(originalValue);
  26561. weights.push(scale);
  26562. }
  26563. else {
  26564. if (holder.animations.length === 2) { // Slerp as soon as we can
  26565. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26566. return refQuaternion;
  26567. }
  26568. quaternions = [];
  26569. weights = [];
  26570. normalizer = holder.totalWeight;
  26571. }
  26572. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26573. var runtimeAnimation = holder.animations[animIndex];
  26574. quaternions.push(runtimeAnimation.currentValue);
  26575. weights.push(runtimeAnimation.weight / normalizer);
  26576. }
  26577. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26578. var cumulativeAmount = 0;
  26579. var cumulativeQuaternion = null;
  26580. for (var index = 0; index < quaternions.length;) {
  26581. if (!cumulativeQuaternion) {
  26582. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26583. cumulativeQuaternion = refQuaternion;
  26584. cumulativeAmount = weights[index] + weights[index + 1];
  26585. index += 2;
  26586. continue;
  26587. }
  26588. cumulativeAmount += weights[index];
  26589. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26590. index++;
  26591. }
  26592. return cumulativeQuaternion;
  26593. };
  26594. Scene.prototype._processLateAnimationBindings = function () {
  26595. if (!this._registeredForLateAnimationBindings.length) {
  26596. return;
  26597. }
  26598. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26599. var target = this._registeredForLateAnimationBindings.data[index];
  26600. for (var path in target._lateAnimationHolders) {
  26601. var holder = target._lateAnimationHolders[path];
  26602. var originalAnimation = holder.animations[0];
  26603. var originalValue = holder.originalValue;
  26604. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26605. var finalValue = target[path];
  26606. if (matrixDecomposeMode) {
  26607. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26608. }
  26609. else {
  26610. var quaternionMode = originalValue.w !== undefined;
  26611. if (quaternionMode) {
  26612. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26613. }
  26614. else {
  26615. var startIndex = 0;
  26616. var normalizer = 1.0;
  26617. if (holder.totalWeight < 1.0) {
  26618. // We need to mix the original value in
  26619. if (originalValue.scale) {
  26620. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26621. }
  26622. else {
  26623. finalValue = originalValue * (1.0 - holder.totalWeight);
  26624. }
  26625. }
  26626. else {
  26627. // We need to normalize the weights
  26628. normalizer = holder.totalWeight;
  26629. var scale_1 = originalAnimation.weight / normalizer;
  26630. if (scale_1 !== 1) {
  26631. if (originalAnimation.currentValue.scale) {
  26632. finalValue = originalAnimation.currentValue.scale(scale_1);
  26633. }
  26634. else {
  26635. finalValue = originalAnimation.currentValue * scale_1;
  26636. }
  26637. }
  26638. else {
  26639. finalValue = originalAnimation.currentValue;
  26640. }
  26641. startIndex = 1;
  26642. }
  26643. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26644. var runtimeAnimation = holder.animations[animIndex];
  26645. var scale = runtimeAnimation.weight / normalizer;
  26646. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26647. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26648. }
  26649. else {
  26650. finalValue += runtimeAnimation.currentValue * scale;
  26651. }
  26652. }
  26653. }
  26654. }
  26655. target[path] = finalValue;
  26656. }
  26657. target._lateAnimationHolders = {};
  26658. }
  26659. this._registeredForLateAnimationBindings.reset();
  26660. };
  26661. // Matrix
  26662. /** @hidden */
  26663. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26664. this._useAlternateCameraConfiguration = active;
  26665. };
  26666. /**
  26667. * Gets the current view matrix
  26668. * @returns a Matrix
  26669. */
  26670. Scene.prototype.getViewMatrix = function () {
  26671. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26672. };
  26673. /**
  26674. * Gets the current projection matrix
  26675. * @returns a Matrix
  26676. */
  26677. Scene.prototype.getProjectionMatrix = function () {
  26678. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26679. };
  26680. /**
  26681. * Gets the current transform matrix
  26682. * @returns a Matrix made of View * Projection
  26683. */
  26684. Scene.prototype.getTransformMatrix = function () {
  26685. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26686. };
  26687. /**
  26688. * Sets the current transform matrix
  26689. * @param view defines the View matrix to use
  26690. * @param projection defines the Projection matrix to use
  26691. */
  26692. Scene.prototype.setTransformMatrix = function (view, projection) {
  26693. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26694. return;
  26695. }
  26696. this._viewUpdateFlag = view.updateFlag;
  26697. this._projectionUpdateFlag = projection.updateFlag;
  26698. this._viewMatrix = view;
  26699. this._projectionMatrix = projection;
  26700. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26701. // Update frustum
  26702. if (!this._frustumPlanes) {
  26703. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26704. }
  26705. else {
  26706. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26707. }
  26708. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26709. var otherCamera = this.activeCamera._alternateCamera;
  26710. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26711. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26712. }
  26713. if (this._sceneUbo.useUbo) {
  26714. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26715. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26716. this._sceneUbo.update();
  26717. }
  26718. };
  26719. /** @hidden */
  26720. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26721. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26722. return;
  26723. }
  26724. this._alternateViewUpdateFlag = view.updateFlag;
  26725. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26726. this._alternateViewMatrix = view;
  26727. this._alternateProjectionMatrix = projection;
  26728. if (!this._alternateTransformMatrix) {
  26729. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26730. }
  26731. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26732. if (!this._alternateSceneUbo) {
  26733. this._createAlternateUbo();
  26734. }
  26735. if (this._alternateSceneUbo.useUbo) {
  26736. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26737. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26738. this._alternateSceneUbo.update();
  26739. }
  26740. };
  26741. /**
  26742. * Gets the uniform buffer used to store scene data
  26743. * @returns a UniformBuffer
  26744. */
  26745. Scene.prototype.getSceneUniformBuffer = function () {
  26746. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26747. };
  26748. /**
  26749. * Gets an unique (relatively to the current scene) Id
  26750. * @returns an unique number for the scene
  26751. */
  26752. Scene.prototype.getUniqueId = function () {
  26753. var result = Scene._uniqueIdCounter;
  26754. Scene._uniqueIdCounter++;
  26755. return result;
  26756. };
  26757. /**
  26758. * Add a mesh to the list of scene's meshes
  26759. * @param newMesh defines the mesh to add
  26760. * @param recursive if all child meshes should also be added to the scene
  26761. */
  26762. Scene.prototype.addMesh = function (newMesh, recursive) {
  26763. var _this = this;
  26764. if (recursive === void 0) { recursive = false; }
  26765. this.meshes.push(newMesh);
  26766. //notify the collision coordinator
  26767. if (this.collisionCoordinator) {
  26768. this.collisionCoordinator.onMeshAdded(newMesh);
  26769. }
  26770. newMesh._resyncLightSources();
  26771. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26772. if (recursive) {
  26773. newMesh.getChildMeshes().forEach(function (m) {
  26774. _this.addMesh(m);
  26775. });
  26776. }
  26777. };
  26778. /**
  26779. * Remove a mesh for the list of scene's meshes
  26780. * @param toRemove defines the mesh to remove
  26781. * @param recursive if all child meshes should also be removed from the scene
  26782. * @returns the index where the mesh was in the mesh list
  26783. */
  26784. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26785. var _this = this;
  26786. if (recursive === void 0) { recursive = false; }
  26787. var index = this.meshes.indexOf(toRemove);
  26788. if (index !== -1) {
  26789. // Remove from the scene if mesh found
  26790. this.meshes.splice(index, 1);
  26791. }
  26792. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26793. if (recursive) {
  26794. toRemove.getChildMeshes().forEach(function (m) {
  26795. _this.removeMesh(m);
  26796. });
  26797. }
  26798. return index;
  26799. };
  26800. /**
  26801. * Add a transform node to the list of scene's transform nodes
  26802. * @param newTransformNode defines the transform node to add
  26803. */
  26804. Scene.prototype.addTransformNode = function (newTransformNode) {
  26805. this.transformNodes.push(newTransformNode);
  26806. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26807. };
  26808. /**
  26809. * Remove a transform node for the list of scene's transform nodes
  26810. * @param toRemove defines the transform node to remove
  26811. * @returns the index where the transform node was in the transform node list
  26812. */
  26813. Scene.prototype.removeTransformNode = function (toRemove) {
  26814. var index = this.transformNodes.indexOf(toRemove);
  26815. if (index !== -1) {
  26816. // Remove from the scene if found
  26817. this.transformNodes.splice(index, 1);
  26818. }
  26819. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26820. return index;
  26821. };
  26822. /**
  26823. * Remove a skeleton for the list of scene's skeletons
  26824. * @param toRemove defines the skeleton to remove
  26825. * @returns the index where the skeleton was in the skeleton list
  26826. */
  26827. Scene.prototype.removeSkeleton = function (toRemove) {
  26828. var index = this.skeletons.indexOf(toRemove);
  26829. if (index !== -1) {
  26830. // Remove from the scene if found
  26831. this.skeletons.splice(index, 1);
  26832. }
  26833. return index;
  26834. };
  26835. /**
  26836. * Remove a morph target for the list of scene's morph targets
  26837. * @param toRemove defines the morph target to remove
  26838. * @returns the index where the morph target was in the morph target list
  26839. */
  26840. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26841. var index = this.morphTargetManagers.indexOf(toRemove);
  26842. if (index !== -1) {
  26843. // Remove from the scene if found
  26844. this.morphTargetManagers.splice(index, 1);
  26845. }
  26846. return index;
  26847. };
  26848. /**
  26849. * Remove a light for the list of scene's lights
  26850. * @param toRemove defines the light to remove
  26851. * @returns the index where the light was in the light list
  26852. */
  26853. Scene.prototype.removeLight = function (toRemove) {
  26854. var index = this.lights.indexOf(toRemove);
  26855. if (index !== -1) {
  26856. // Remove from meshes
  26857. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26858. var mesh = _a[_i];
  26859. mesh._removeLightSource(toRemove);
  26860. }
  26861. // Remove from the scene if mesh found
  26862. this.lights.splice(index, 1);
  26863. this.sortLightsByPriority();
  26864. }
  26865. this.onLightRemovedObservable.notifyObservers(toRemove);
  26866. return index;
  26867. };
  26868. /**
  26869. * Remove a camera for the list of scene's cameras
  26870. * @param toRemove defines the camera to remove
  26871. * @returns the index where the camera was in the camera list
  26872. */
  26873. Scene.prototype.removeCamera = function (toRemove) {
  26874. var index = this.cameras.indexOf(toRemove);
  26875. if (index !== -1) {
  26876. // Remove from the scene if mesh found
  26877. this.cameras.splice(index, 1);
  26878. }
  26879. // Remove from activeCameras
  26880. var index2 = this.activeCameras.indexOf(toRemove);
  26881. if (index2 !== -1) {
  26882. // Remove from the scene if mesh found
  26883. this.activeCameras.splice(index2, 1);
  26884. }
  26885. // Reset the activeCamera
  26886. if (this.activeCamera === toRemove) {
  26887. if (this.cameras.length > 0) {
  26888. this.activeCamera = this.cameras[0];
  26889. }
  26890. else {
  26891. this.activeCamera = null;
  26892. }
  26893. }
  26894. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26895. return index;
  26896. };
  26897. /**
  26898. * Remove a particle system for the list of scene's particle systems
  26899. * @param toRemove defines the particle system to remove
  26900. * @returns the index where the particle system was in the particle system list
  26901. */
  26902. Scene.prototype.removeParticleSystem = function (toRemove) {
  26903. var index = this.particleSystems.indexOf(toRemove);
  26904. if (index !== -1) {
  26905. this.particleSystems.splice(index, 1);
  26906. }
  26907. return index;
  26908. };
  26909. /**
  26910. * Remove a animation for the list of scene's animations
  26911. * @param toRemove defines the animation to remove
  26912. * @returns the index where the animation was in the animation list
  26913. */
  26914. Scene.prototype.removeAnimation = function (toRemove) {
  26915. var index = this.animations.indexOf(toRemove);
  26916. if (index !== -1) {
  26917. this.animations.splice(index, 1);
  26918. }
  26919. return index;
  26920. };
  26921. /**
  26922. * Removes the given animation group from this scene.
  26923. * @param toRemove The animation group to remove
  26924. * @returns The index of the removed animation group
  26925. */
  26926. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26927. var index = this.animationGroups.indexOf(toRemove);
  26928. if (index !== -1) {
  26929. this.animationGroups.splice(index, 1);
  26930. }
  26931. return index;
  26932. };
  26933. /**
  26934. * Removes the given multi-material from this scene.
  26935. * @param toRemove The multi-material to remove
  26936. * @returns The index of the removed multi-material
  26937. */
  26938. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26939. var index = this.multiMaterials.indexOf(toRemove);
  26940. if (index !== -1) {
  26941. this.multiMaterials.splice(index, 1);
  26942. }
  26943. return index;
  26944. };
  26945. /**
  26946. * Removes the given material from this scene.
  26947. * @param toRemove The material to remove
  26948. * @returns The index of the removed material
  26949. */
  26950. Scene.prototype.removeMaterial = function (toRemove) {
  26951. var index = this.materials.indexOf(toRemove);
  26952. if (index !== -1) {
  26953. this.materials.splice(index, 1);
  26954. }
  26955. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  26956. return index;
  26957. };
  26958. /**
  26959. * Removes the given action manager from this scene.
  26960. * @param toRemove The action manager to remove
  26961. * @returns The index of the removed action manager
  26962. */
  26963. Scene.prototype.removeActionManager = function (toRemove) {
  26964. var index = this.actionManagers.indexOf(toRemove);
  26965. if (index !== -1) {
  26966. this.actionManagers.splice(index, 1);
  26967. }
  26968. return index;
  26969. };
  26970. /**
  26971. * Removes the given texture from this scene.
  26972. * @param toRemove The texture to remove
  26973. * @returns The index of the removed texture
  26974. */
  26975. Scene.prototype.removeTexture = function (toRemove) {
  26976. var index = this.textures.indexOf(toRemove);
  26977. if (index !== -1) {
  26978. this.textures.splice(index, 1);
  26979. }
  26980. this.onTextureRemovedObservable.notifyObservers(toRemove);
  26981. return index;
  26982. };
  26983. /**
  26984. * Adds the given light to this scene
  26985. * @param newLight The light to add
  26986. */
  26987. Scene.prototype.addLight = function (newLight) {
  26988. this.lights.push(newLight);
  26989. this.sortLightsByPriority();
  26990. // Add light to all meshes (To support if the light is removed and then readded)
  26991. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26992. var mesh = _a[_i];
  26993. if (mesh._lightSources.indexOf(newLight) === -1) {
  26994. mesh._lightSources.push(newLight);
  26995. mesh._resyncLightSources();
  26996. }
  26997. }
  26998. this.onNewLightAddedObservable.notifyObservers(newLight);
  26999. };
  27000. /**
  27001. * Sorts the list list based on light priorities
  27002. */
  27003. Scene.prototype.sortLightsByPriority = function () {
  27004. if (this.requireLightSorting) {
  27005. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27006. }
  27007. };
  27008. /**
  27009. * Adds the given camera to this scene
  27010. * @param newCamera The camera to add
  27011. */
  27012. Scene.prototype.addCamera = function (newCamera) {
  27013. this.cameras.push(newCamera);
  27014. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27015. };
  27016. /**
  27017. * Adds the given skeleton to this scene
  27018. * @param newSkeleton The skeleton to add
  27019. */
  27020. Scene.prototype.addSkeleton = function (newSkeleton) {
  27021. this.skeletons.push(newSkeleton);
  27022. };
  27023. /**
  27024. * Adds the given particle system to this scene
  27025. * @param newParticleSystem The particle system to add
  27026. */
  27027. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27028. this.particleSystems.push(newParticleSystem);
  27029. };
  27030. /**
  27031. * Adds the given animation to this scene
  27032. * @param newAnimation The animation to add
  27033. */
  27034. Scene.prototype.addAnimation = function (newAnimation) {
  27035. this.animations.push(newAnimation);
  27036. };
  27037. /**
  27038. * Adds the given animation group to this scene.
  27039. * @param newAnimationGroup The animation group to add
  27040. */
  27041. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27042. this.animationGroups.push(newAnimationGroup);
  27043. };
  27044. /**
  27045. * Adds the given multi-material to this scene
  27046. * @param newMultiMaterial The multi-material to add
  27047. */
  27048. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27049. this.multiMaterials.push(newMultiMaterial);
  27050. };
  27051. /**
  27052. * Adds the given material to this scene
  27053. * @param newMaterial The material to add
  27054. */
  27055. Scene.prototype.addMaterial = function (newMaterial) {
  27056. this.materials.push(newMaterial);
  27057. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27058. };
  27059. /**
  27060. * Adds the given morph target to this scene
  27061. * @param newMorphTargetManager The morph target to add
  27062. */
  27063. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27064. this.morphTargetManagers.push(newMorphTargetManager);
  27065. };
  27066. /**
  27067. * Adds the given geometry to this scene
  27068. * @param newGeometry The geometry to add
  27069. */
  27070. Scene.prototype.addGeometry = function (newGeometry) {
  27071. this.geometries.push(newGeometry);
  27072. };
  27073. /**
  27074. * Adds the given action manager to this scene
  27075. * @param newActionManager The action manager to add
  27076. */
  27077. Scene.prototype.addActionManager = function (newActionManager) {
  27078. this.actionManagers.push(newActionManager);
  27079. };
  27080. /**
  27081. * Adds the given texture to this scene.
  27082. * @param newTexture The texture to add
  27083. */
  27084. Scene.prototype.addTexture = function (newTexture) {
  27085. this.textures.push(newTexture);
  27086. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27087. };
  27088. /**
  27089. * Switch active camera
  27090. * @param newCamera defines the new active camera
  27091. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27092. */
  27093. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27094. if (attachControl === void 0) { attachControl = true; }
  27095. var canvas = this._engine.getRenderingCanvas();
  27096. if (!canvas) {
  27097. return;
  27098. }
  27099. if (this.activeCamera) {
  27100. this.activeCamera.detachControl(canvas);
  27101. }
  27102. this.activeCamera = newCamera;
  27103. if (attachControl) {
  27104. newCamera.attachControl(canvas);
  27105. }
  27106. };
  27107. /**
  27108. * sets the active camera of the scene using its ID
  27109. * @param id defines the camera's ID
  27110. * @return the new active camera or null if none found.
  27111. */
  27112. Scene.prototype.setActiveCameraByID = function (id) {
  27113. var camera = this.getCameraByID(id);
  27114. if (camera) {
  27115. this.activeCamera = camera;
  27116. return camera;
  27117. }
  27118. return null;
  27119. };
  27120. /**
  27121. * sets the active camera of the scene using its name
  27122. * @param name defines the camera's name
  27123. * @returns the new active camera or null if none found.
  27124. */
  27125. Scene.prototype.setActiveCameraByName = function (name) {
  27126. var camera = this.getCameraByName(name);
  27127. if (camera) {
  27128. this.activeCamera = camera;
  27129. return camera;
  27130. }
  27131. return null;
  27132. };
  27133. /**
  27134. * get an animation group using its name
  27135. * @param name defines the material's name
  27136. * @return the animation group or null if none found.
  27137. */
  27138. Scene.prototype.getAnimationGroupByName = function (name) {
  27139. for (var index = 0; index < this.animationGroups.length; index++) {
  27140. if (this.animationGroups[index].name === name) {
  27141. return this.animationGroups[index];
  27142. }
  27143. }
  27144. return null;
  27145. };
  27146. /**
  27147. * get a material using its id
  27148. * @param id defines the material's ID
  27149. * @return the material or null if none found.
  27150. */
  27151. Scene.prototype.getMaterialByID = function (id) {
  27152. for (var index = 0; index < this.materials.length; index++) {
  27153. if (this.materials[index].id === id) {
  27154. return this.materials[index];
  27155. }
  27156. }
  27157. return null;
  27158. };
  27159. /**
  27160. * Gets a material using its name
  27161. * @param name defines the material's name
  27162. * @return the material or null if none found.
  27163. */
  27164. Scene.prototype.getMaterialByName = function (name) {
  27165. for (var index = 0; index < this.materials.length; index++) {
  27166. if (this.materials[index].name === name) {
  27167. return this.materials[index];
  27168. }
  27169. }
  27170. return null;
  27171. };
  27172. /**
  27173. * Gets a camera using its id
  27174. * @param id defines the id to look for
  27175. * @returns the camera or null if not found
  27176. */
  27177. Scene.prototype.getCameraByID = function (id) {
  27178. for (var index = 0; index < this.cameras.length; index++) {
  27179. if (this.cameras[index].id === id) {
  27180. return this.cameras[index];
  27181. }
  27182. }
  27183. return null;
  27184. };
  27185. /**
  27186. * Gets a camera using its unique id
  27187. * @param uniqueId defines the unique id to look for
  27188. * @returns the camera or null if not found
  27189. */
  27190. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27191. for (var index = 0; index < this.cameras.length; index++) {
  27192. if (this.cameras[index].uniqueId === uniqueId) {
  27193. return this.cameras[index];
  27194. }
  27195. }
  27196. return null;
  27197. };
  27198. /**
  27199. * Gets a camera using its name
  27200. * @param name defines the camera's name
  27201. * @return the camera or null if none found.
  27202. */
  27203. Scene.prototype.getCameraByName = function (name) {
  27204. for (var index = 0; index < this.cameras.length; index++) {
  27205. if (this.cameras[index].name === name) {
  27206. return this.cameras[index];
  27207. }
  27208. }
  27209. return null;
  27210. };
  27211. /**
  27212. * Gets a bone using its id
  27213. * @param id defines the bone's id
  27214. * @return the bone or null if not found
  27215. */
  27216. Scene.prototype.getBoneByID = function (id) {
  27217. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27218. var skeleton = this.skeletons[skeletonIndex];
  27219. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27220. if (skeleton.bones[boneIndex].id === id) {
  27221. return skeleton.bones[boneIndex];
  27222. }
  27223. }
  27224. }
  27225. return null;
  27226. };
  27227. /**
  27228. * Gets a bone using its id
  27229. * @param name defines the bone's name
  27230. * @return the bone or null if not found
  27231. */
  27232. Scene.prototype.getBoneByName = function (name) {
  27233. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27234. var skeleton = this.skeletons[skeletonIndex];
  27235. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27236. if (skeleton.bones[boneIndex].name === name) {
  27237. return skeleton.bones[boneIndex];
  27238. }
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. /**
  27244. * Gets a light node using its name
  27245. * @param name defines the the light's name
  27246. * @return the light or null if none found.
  27247. */
  27248. Scene.prototype.getLightByName = function (name) {
  27249. for (var index = 0; index < this.lights.length; index++) {
  27250. if (this.lights[index].name === name) {
  27251. return this.lights[index];
  27252. }
  27253. }
  27254. return null;
  27255. };
  27256. /**
  27257. * Gets a light node using its id
  27258. * @param id defines the light's id
  27259. * @return the light or null if none found.
  27260. */
  27261. Scene.prototype.getLightByID = function (id) {
  27262. for (var index = 0; index < this.lights.length; index++) {
  27263. if (this.lights[index].id === id) {
  27264. return this.lights[index];
  27265. }
  27266. }
  27267. return null;
  27268. };
  27269. /**
  27270. * Gets a light node using its scene-generated unique ID
  27271. * @param uniqueId defines the light's unique id
  27272. * @return the light or null if none found.
  27273. */
  27274. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27275. for (var index = 0; index < this.lights.length; index++) {
  27276. if (this.lights[index].uniqueId === uniqueId) {
  27277. return this.lights[index];
  27278. }
  27279. }
  27280. return null;
  27281. };
  27282. /**
  27283. * Gets a particle system by id
  27284. * @param id defines the particle system id
  27285. * @return the corresponding system or null if none found
  27286. */
  27287. Scene.prototype.getParticleSystemByID = function (id) {
  27288. for (var index = 0; index < this.particleSystems.length; index++) {
  27289. if (this.particleSystems[index].id === id) {
  27290. return this.particleSystems[index];
  27291. }
  27292. }
  27293. return null;
  27294. };
  27295. /**
  27296. * Gets a geometry using its ID
  27297. * @param id defines the geometry's id
  27298. * @return the geometry or null if none found.
  27299. */
  27300. Scene.prototype.getGeometryByID = function (id) {
  27301. for (var index = 0; index < this.geometries.length; index++) {
  27302. if (this.geometries[index].id === id) {
  27303. return this.geometries[index];
  27304. }
  27305. }
  27306. return null;
  27307. };
  27308. /**
  27309. * Add a new geometry to this scene
  27310. * @param geometry defines the geometry to be added to the scene.
  27311. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27312. * @return a boolean defining if the geometry was added or not
  27313. */
  27314. Scene.prototype.pushGeometry = function (geometry, force) {
  27315. if (!force && this.getGeometryByID(geometry.id)) {
  27316. return false;
  27317. }
  27318. this.geometries.push(geometry);
  27319. //notify the collision coordinator
  27320. if (this.collisionCoordinator) {
  27321. this.collisionCoordinator.onGeometryAdded(geometry);
  27322. }
  27323. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27324. return true;
  27325. };
  27326. /**
  27327. * Removes an existing geometry
  27328. * @param geometry defines the geometry to be removed from the scene
  27329. * @return a boolean defining if the geometry was removed or not
  27330. */
  27331. Scene.prototype.removeGeometry = function (geometry) {
  27332. var index = this.geometries.indexOf(geometry);
  27333. if (index > -1) {
  27334. this.geometries.splice(index, 1);
  27335. //notify the collision coordinator
  27336. if (this.collisionCoordinator) {
  27337. this.collisionCoordinator.onGeometryDeleted(geometry);
  27338. }
  27339. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27340. return true;
  27341. }
  27342. return false;
  27343. };
  27344. /**
  27345. * Gets the list of geometries attached to the scene
  27346. * @returns an array of Geometry
  27347. */
  27348. Scene.prototype.getGeometries = function () {
  27349. return this.geometries;
  27350. };
  27351. /**
  27352. * Gets the first added mesh found of a given ID
  27353. * @param id defines the id to search for
  27354. * @return the mesh found or null if not found at all
  27355. */
  27356. Scene.prototype.getMeshByID = function (id) {
  27357. for (var index = 0; index < this.meshes.length; index++) {
  27358. if (this.meshes[index].id === id) {
  27359. return this.meshes[index];
  27360. }
  27361. }
  27362. return null;
  27363. };
  27364. /**
  27365. * Gets a list of meshes using their id
  27366. * @param id defines the id to search for
  27367. * @returns a list of meshes
  27368. */
  27369. Scene.prototype.getMeshesByID = function (id) {
  27370. return this.meshes.filter(function (m) {
  27371. return m.id === id;
  27372. });
  27373. };
  27374. /**
  27375. * Gets the first added transform node found of a given ID
  27376. * @param id defines the id to search for
  27377. * @return the found transform node or null if not found at all.
  27378. */
  27379. Scene.prototype.getTransformNodeByID = function (id) {
  27380. for (var index = 0; index < this.transformNodes.length; index++) {
  27381. if (this.transformNodes[index].id === id) {
  27382. return this.transformNodes[index];
  27383. }
  27384. }
  27385. return null;
  27386. };
  27387. /**
  27388. * Gets a list of transform nodes using their id
  27389. * @param id defines the id to search for
  27390. * @returns a list of transform nodes
  27391. */
  27392. Scene.prototype.getTransformNodesByID = function (id) {
  27393. return this.transformNodes.filter(function (m) {
  27394. return m.id === id;
  27395. });
  27396. };
  27397. /**
  27398. * Gets a mesh with its auto-generated unique id
  27399. * @param uniqueId defines the unique id to search for
  27400. * @return the found mesh or null if not found at all.
  27401. */
  27402. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27403. for (var index = 0; index < this.meshes.length; index++) {
  27404. if (this.meshes[index].uniqueId === uniqueId) {
  27405. return this.meshes[index];
  27406. }
  27407. }
  27408. return null;
  27409. };
  27410. /**
  27411. * Gets a the last added mesh using a given id
  27412. * @param id defines the id to search for
  27413. * @return the found mesh or null if not found at all.
  27414. */
  27415. Scene.prototype.getLastMeshByID = function (id) {
  27416. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27417. if (this.meshes[index].id === id) {
  27418. return this.meshes[index];
  27419. }
  27420. }
  27421. return null;
  27422. };
  27423. /**
  27424. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27425. * @param id defines the id to search for
  27426. * @return the found node or null if not found at all
  27427. */
  27428. Scene.prototype.getLastEntryByID = function (id) {
  27429. var index;
  27430. for (index = this.meshes.length - 1; index >= 0; index--) {
  27431. if (this.meshes[index].id === id) {
  27432. return this.meshes[index];
  27433. }
  27434. }
  27435. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27436. if (this.transformNodes[index].id === id) {
  27437. return this.transformNodes[index];
  27438. }
  27439. }
  27440. for (index = this.cameras.length - 1; index >= 0; index--) {
  27441. if (this.cameras[index].id === id) {
  27442. return this.cameras[index];
  27443. }
  27444. }
  27445. for (index = this.lights.length - 1; index >= 0; index--) {
  27446. if (this.lights[index].id === id) {
  27447. return this.lights[index];
  27448. }
  27449. }
  27450. return null;
  27451. };
  27452. /**
  27453. * Gets a node (Mesh, Camera, Light) using a given id
  27454. * @param id defines the id to search for
  27455. * @return the found node or null if not found at all
  27456. */
  27457. Scene.prototype.getNodeByID = function (id) {
  27458. var mesh = this.getMeshByID(id);
  27459. if (mesh) {
  27460. return mesh;
  27461. }
  27462. var light = this.getLightByID(id);
  27463. if (light) {
  27464. return light;
  27465. }
  27466. var camera = this.getCameraByID(id);
  27467. if (camera) {
  27468. return camera;
  27469. }
  27470. var bone = this.getBoneByID(id);
  27471. return bone;
  27472. };
  27473. /**
  27474. * Gets a node (Mesh, Camera, Light) using a given name
  27475. * @param name defines the name to search for
  27476. * @return the found node or null if not found at all.
  27477. */
  27478. Scene.prototype.getNodeByName = function (name) {
  27479. var mesh = this.getMeshByName(name);
  27480. if (mesh) {
  27481. return mesh;
  27482. }
  27483. var light = this.getLightByName(name);
  27484. if (light) {
  27485. return light;
  27486. }
  27487. var camera = this.getCameraByName(name);
  27488. if (camera) {
  27489. return camera;
  27490. }
  27491. var bone = this.getBoneByName(name);
  27492. return bone;
  27493. };
  27494. /**
  27495. * Gets a mesh using a given name
  27496. * @param name defines the name to search for
  27497. * @return the found mesh or null if not found at all.
  27498. */
  27499. Scene.prototype.getMeshByName = function (name) {
  27500. for (var index = 0; index < this.meshes.length; index++) {
  27501. if (this.meshes[index].name === name) {
  27502. return this.meshes[index];
  27503. }
  27504. }
  27505. return null;
  27506. };
  27507. /**
  27508. * Gets a transform node using a given name
  27509. * @param name defines the name to search for
  27510. * @return the found transform node or null if not found at all.
  27511. */
  27512. Scene.prototype.getTransformNodeByName = function (name) {
  27513. for (var index = 0; index < this.transformNodes.length; index++) {
  27514. if (this.transformNodes[index].name === name) {
  27515. return this.transformNodes[index];
  27516. }
  27517. }
  27518. return null;
  27519. };
  27520. /**
  27521. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27522. * @param id defines the id to search for
  27523. * @return the found skeleton or null if not found at all.
  27524. */
  27525. Scene.prototype.getLastSkeletonByID = function (id) {
  27526. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27527. if (this.skeletons[index].id === id) {
  27528. return this.skeletons[index];
  27529. }
  27530. }
  27531. return null;
  27532. };
  27533. /**
  27534. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27535. * @param id defines the id to search for
  27536. * @return the found skeleton or null if not found at all.
  27537. */
  27538. Scene.prototype.getSkeletonById = function (id) {
  27539. for (var index = 0; index < this.skeletons.length; index++) {
  27540. if (this.skeletons[index].id === id) {
  27541. return this.skeletons[index];
  27542. }
  27543. }
  27544. return null;
  27545. };
  27546. /**
  27547. * Gets a skeleton using a given name
  27548. * @param name defines the name to search for
  27549. * @return the found skeleton or null if not found at all.
  27550. */
  27551. Scene.prototype.getSkeletonByName = function (name) {
  27552. for (var index = 0; index < this.skeletons.length; index++) {
  27553. if (this.skeletons[index].name === name) {
  27554. return this.skeletons[index];
  27555. }
  27556. }
  27557. return null;
  27558. };
  27559. /**
  27560. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27561. * @param id defines the id to search for
  27562. * @return the found morph target manager or null if not found at all.
  27563. */
  27564. Scene.prototype.getMorphTargetManagerById = function (id) {
  27565. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27566. if (this.morphTargetManagers[index].uniqueId === id) {
  27567. return this.morphTargetManagers[index];
  27568. }
  27569. }
  27570. return null;
  27571. };
  27572. /**
  27573. * Gets a boolean indicating if the given mesh is active
  27574. * @param mesh defines the mesh to look for
  27575. * @returns true if the mesh is in the active list
  27576. */
  27577. Scene.prototype.isActiveMesh = function (mesh) {
  27578. return (this._activeMeshes.indexOf(mesh) !== -1);
  27579. };
  27580. Object.defineProperty(Scene.prototype, "uid", {
  27581. /**
  27582. * Return a unique id as a string which can serve as an identifier for the scene
  27583. */
  27584. get: function () {
  27585. if (!this._uid) {
  27586. this._uid = BABYLON.Tools.RandomId();
  27587. }
  27588. return this._uid;
  27589. },
  27590. enumerable: true,
  27591. configurable: true
  27592. });
  27593. /**
  27594. * Add an externaly attached data from its key.
  27595. * This method call will fail and return false, if such key already exists.
  27596. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27597. * @param key the unique key that identifies the data
  27598. * @param data the data object to associate to the key for this Engine instance
  27599. * @return true if no such key were already present and the data was added successfully, false otherwise
  27600. */
  27601. Scene.prototype.addExternalData = function (key, data) {
  27602. if (!this._externalData) {
  27603. this._externalData = new BABYLON.StringDictionary();
  27604. }
  27605. return this._externalData.add(key, data);
  27606. };
  27607. /**
  27608. * Get an externaly attached data from its key
  27609. * @param key the unique key that identifies the data
  27610. * @return the associated data, if present (can be null), or undefined if not present
  27611. */
  27612. Scene.prototype.getExternalData = function (key) {
  27613. if (!this._externalData) {
  27614. return null;
  27615. }
  27616. return this._externalData.get(key);
  27617. };
  27618. /**
  27619. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27620. * @param key the unique key that identifies the data
  27621. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27622. * @return the associated data, can be null if the factory returned null.
  27623. */
  27624. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27625. if (!this._externalData) {
  27626. this._externalData = new BABYLON.StringDictionary();
  27627. }
  27628. return this._externalData.getOrAddWithFactory(key, factory);
  27629. };
  27630. /**
  27631. * Remove an externaly attached data from the Engine instance
  27632. * @param key the unique key that identifies the data
  27633. * @return true if the data was successfully removed, false if it doesn't exist
  27634. */
  27635. Scene.prototype.removeExternalData = function (key) {
  27636. return this._externalData.remove(key);
  27637. };
  27638. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27639. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27640. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27641. var step = _a[_i];
  27642. step.action(mesh, subMesh);
  27643. }
  27644. var material = subMesh.getMaterial();
  27645. if (material !== null && material !== undefined) {
  27646. // Render targets
  27647. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27648. if (this._processedMaterials.indexOf(material) === -1) {
  27649. this._processedMaterials.push(material);
  27650. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27651. }
  27652. }
  27653. // Dispatch
  27654. this._activeIndices.addCount(subMesh.indexCount, false);
  27655. this._renderingManager.dispatch(subMesh, mesh, material);
  27656. }
  27657. }
  27658. };
  27659. /**
  27660. * Clear the processed materials smart array preventing retention point in material dispose.
  27661. */
  27662. Scene.prototype.freeProcessedMaterials = function () {
  27663. this._processedMaterials.dispose();
  27664. };
  27665. /**
  27666. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27667. */
  27668. Scene.prototype.freeActiveMeshes = function () {
  27669. this._activeMeshes.dispose();
  27670. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27671. this.activeCamera._activeMeshes.dispose();
  27672. }
  27673. if (this.activeCameras) {
  27674. for (var i = 0; i < this.activeCameras.length; i++) {
  27675. var activeCamera = this.activeCameras[i];
  27676. if (activeCamera && activeCamera._activeMeshes) {
  27677. activeCamera._activeMeshes.dispose();
  27678. }
  27679. }
  27680. }
  27681. };
  27682. /**
  27683. * Clear the info related to rendering groups preventing retention points during dispose.
  27684. */
  27685. Scene.prototype.freeRenderingGroups = function () {
  27686. if (this._renderingManager) {
  27687. this._renderingManager.freeRenderingGroups();
  27688. }
  27689. if (this.textures) {
  27690. for (var i = 0; i < this.textures.length; i++) {
  27691. var texture = this.textures[i];
  27692. if (texture && texture.renderList) {
  27693. texture.freeRenderingGroups();
  27694. }
  27695. }
  27696. }
  27697. };
  27698. /** @hidden */
  27699. Scene.prototype._isInIntermediateRendering = function () {
  27700. return this._intermediateRendering;
  27701. };
  27702. /**
  27703. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27704. * @returns the current scene
  27705. */
  27706. Scene.prototype.freezeActiveMeshes = function () {
  27707. if (!this.activeCamera) {
  27708. return this;
  27709. }
  27710. if (!this._frustumPlanes) {
  27711. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27712. }
  27713. this._evaluateActiveMeshes();
  27714. this._activeMeshesFrozen = true;
  27715. return this;
  27716. };
  27717. /**
  27718. * Use this function to restart evaluating active meshes on every frame
  27719. * @returns the current scene
  27720. */
  27721. Scene.prototype.unfreezeActiveMeshes = function () {
  27722. this._activeMeshesFrozen = false;
  27723. return this;
  27724. };
  27725. Scene.prototype._evaluateActiveMeshes = function () {
  27726. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27727. return;
  27728. }
  27729. if (!this.activeCamera) {
  27730. return;
  27731. }
  27732. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27733. this.activeCamera._activeMeshes.reset();
  27734. this._activeMeshes.reset();
  27735. this._renderingManager.reset();
  27736. this._processedMaterials.reset();
  27737. this._activeParticleSystems.reset();
  27738. this._activeSkeletons.reset();
  27739. this._softwareSkinnedMeshes.reset();
  27740. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27741. var step = _a[_i];
  27742. step.action();
  27743. }
  27744. // Determine mesh candidates
  27745. var meshes = this.getActiveMeshCandidates();
  27746. // Check each mesh
  27747. var len = meshes.length;
  27748. for (var i = 0; i < len; i++) {
  27749. var mesh = meshes.data[i];
  27750. if (mesh.isBlocked) {
  27751. continue;
  27752. }
  27753. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27754. if (!mesh.isReady() || !mesh.isEnabled()) {
  27755. continue;
  27756. }
  27757. mesh.computeWorldMatrix();
  27758. // Intersections
  27759. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27760. this._meshesForIntersections.pushNoDuplicate(mesh);
  27761. }
  27762. // Switch to current LOD
  27763. var meshLOD = mesh.getLOD(this.activeCamera);
  27764. if (meshLOD === undefined || meshLOD === null) {
  27765. continue;
  27766. }
  27767. mesh._preActivate();
  27768. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27769. this._activeMeshes.push(mesh);
  27770. this.activeCamera._activeMeshes.push(mesh);
  27771. mesh._activate(this._renderId);
  27772. if (meshLOD !== mesh) {
  27773. meshLOD._activate(this._renderId);
  27774. }
  27775. this._activeMesh(mesh, meshLOD);
  27776. }
  27777. }
  27778. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27779. // Particle systems
  27780. if (this.particlesEnabled) {
  27781. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27782. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27783. var particleSystem = this.particleSystems[particleIndex];
  27784. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27785. continue;
  27786. }
  27787. var emitter = particleSystem.emitter;
  27788. if (!emitter.position || emitter.isEnabled()) {
  27789. this._activeParticleSystems.push(particleSystem);
  27790. particleSystem.animate();
  27791. this._renderingManager.dispatchParticles(particleSystem);
  27792. }
  27793. }
  27794. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27795. }
  27796. };
  27797. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27798. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27799. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27800. mesh.skeleton.prepare();
  27801. }
  27802. if (!mesh.computeBonesUsingShaders) {
  27803. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27804. }
  27805. }
  27806. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27807. var step = _a[_i];
  27808. step.action(sourceMesh, mesh);
  27809. }
  27810. if (mesh !== undefined && mesh !== null
  27811. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27812. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27813. var len = subMeshes.length;
  27814. for (var i = 0; i < len; i++) {
  27815. var subMesh = subMeshes.data[i];
  27816. this._evaluateSubMesh(subMesh, mesh);
  27817. }
  27818. }
  27819. };
  27820. /**
  27821. * Update the transform matrix to update from the current active camera
  27822. * @param force defines a boolean used to force the update even if cache is up to date
  27823. */
  27824. Scene.prototype.updateTransformMatrix = function (force) {
  27825. if (!this.activeCamera) {
  27826. return;
  27827. }
  27828. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27829. };
  27830. /**
  27831. * 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)
  27832. * @param alternateCamera defines the camera to use
  27833. */
  27834. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27835. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27836. };
  27837. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27838. if (camera && camera._skipRendering) {
  27839. return;
  27840. }
  27841. var engine = this._engine;
  27842. this.activeCamera = camera;
  27843. if (!this.activeCamera)
  27844. throw new Error("Active camera not set");
  27845. // Viewport
  27846. engine.setViewport(this.activeCamera.viewport);
  27847. // Camera
  27848. this.resetCachedMaterial();
  27849. this._renderId++;
  27850. this.updateTransformMatrix();
  27851. if (camera._alternateCamera) {
  27852. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27853. this._alternateRendering = true;
  27854. }
  27855. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27856. // Meshes
  27857. this._evaluateActiveMeshes();
  27858. // Software skinning
  27859. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27860. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27861. mesh.applySkeleton(mesh.skeleton);
  27862. }
  27863. // Render targets
  27864. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27865. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27866. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27867. }
  27868. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27869. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27870. }
  27871. // Collects render targets from external components.
  27872. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27873. var step = _a[_i];
  27874. step.action(this._renderTargets);
  27875. }
  27876. if (this.renderTargetsEnabled) {
  27877. this._intermediateRendering = true;
  27878. if (this._renderTargets.length > 0) {
  27879. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27880. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27881. var renderTarget = this._renderTargets.data[renderIndex];
  27882. if (renderTarget._shouldRender()) {
  27883. this._renderId++;
  27884. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27885. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27886. }
  27887. }
  27888. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27889. this._renderId++;
  27890. }
  27891. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27892. var step = _c[_b];
  27893. step.action(this.activeCamera);
  27894. }
  27895. this._intermediateRendering = false;
  27896. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27897. }
  27898. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27899. // Prepare Frame
  27900. if (this.postProcessManager) {
  27901. this.postProcessManager._prepareFrame();
  27902. }
  27903. // Before Camera Draw
  27904. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27905. var step = _e[_d];
  27906. step.action(this.activeCamera);
  27907. }
  27908. // Render
  27909. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27910. this._renderingManager.render(null, null, true, true);
  27911. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27912. // After Camera Draw
  27913. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27914. var step = _g[_f];
  27915. step.action(this.activeCamera);
  27916. }
  27917. // Finalize frame
  27918. if (this.postProcessManager) {
  27919. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27920. }
  27921. // Reset some special arrays
  27922. this._renderTargets.reset();
  27923. this._alternateRendering = false;
  27924. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27925. };
  27926. Scene.prototype._processSubCameras = function (camera) {
  27927. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27928. this._renderForCamera(camera);
  27929. return;
  27930. }
  27931. // rig cameras
  27932. for (var index = 0; index < camera._rigCameras.length; index++) {
  27933. this._renderForCamera(camera._rigCameras[index], camera);
  27934. }
  27935. this.activeCamera = camera;
  27936. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27937. };
  27938. Scene.prototype._checkIntersections = function () {
  27939. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27940. var sourceMesh = this._meshesForIntersections.data[index];
  27941. if (!sourceMesh.actionManager) {
  27942. continue;
  27943. }
  27944. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27945. var action = sourceMesh.actionManager.actions[actionIndex];
  27946. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27947. var parameters = action.getTriggerParameter();
  27948. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27949. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27950. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27951. if (areIntersecting && currentIntersectionInProgress === -1) {
  27952. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27953. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27954. sourceMesh._intersectionsInProgress.push(otherMesh);
  27955. }
  27956. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27957. sourceMesh._intersectionsInProgress.push(otherMesh);
  27958. }
  27959. }
  27960. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27961. //They intersected, and now they don't.
  27962. //is this trigger an exit trigger? execute an event.
  27963. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27964. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27965. }
  27966. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27967. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27968. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27969. return otherMesh === parameterMesh;
  27970. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27971. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27972. }
  27973. }
  27974. }
  27975. }
  27976. }
  27977. };
  27978. /** @hidden */
  27979. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27980. // Do nothing. Code will be replaced if physics engine component is referenced
  27981. };
  27982. /**
  27983. * Render the scene
  27984. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27985. */
  27986. Scene.prototype.render = function (updateCameras) {
  27987. if (updateCameras === void 0) { updateCameras = true; }
  27988. if (this.isDisposed) {
  27989. return;
  27990. }
  27991. this._frameId++;
  27992. // Register components that have been associated lately to the scene.
  27993. this._registerTransientComponents();
  27994. this._activeParticles.fetchNewFrame();
  27995. this._totalVertices.fetchNewFrame();
  27996. this._activeIndices.fetchNewFrame();
  27997. this._activeBones.fetchNewFrame();
  27998. this._meshesForIntersections.reset();
  27999. this.resetCachedMaterial();
  28000. this.onBeforeAnimationsObservable.notifyObservers(this);
  28001. // Actions
  28002. if (this.actionManager) {
  28003. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28004. }
  28005. if (this._engine.isDeterministicLockStep()) {
  28006. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28007. var defaultFPS = (60.0 / 1000.0);
  28008. var defaultFrameTime = this.getDeterministicFrameTime();
  28009. var stepsTaken = 0;
  28010. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28011. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28012. internalSteps = Math.min(internalSteps, maxSubSteps);
  28013. do {
  28014. this.onBeforeStepObservable.notifyObservers(this);
  28015. // Animations
  28016. this._animationRatio = defaultFrameTime * defaultFPS;
  28017. this._animate();
  28018. this.onAfterAnimationsObservable.notifyObservers(this);
  28019. // Physics
  28020. this._advancePhysicsEngineStep(defaultFrameTime);
  28021. this.onAfterStepObservable.notifyObservers(this);
  28022. this._currentStepId++;
  28023. stepsTaken++;
  28024. deltaTime -= defaultFrameTime;
  28025. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28026. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28027. }
  28028. else {
  28029. // Animations
  28030. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28031. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28032. this._animate();
  28033. this.onAfterAnimationsObservable.notifyObservers(this);
  28034. // Physics
  28035. this._advancePhysicsEngineStep(deltaTime);
  28036. }
  28037. // Before camera update steps
  28038. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28039. var step = _a[_i];
  28040. step.action();
  28041. }
  28042. // Update Cameras
  28043. if (updateCameras) {
  28044. if (this.activeCameras.length > 0) {
  28045. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28046. var camera = this.activeCameras[cameraIndex];
  28047. camera.update();
  28048. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28049. // rig cameras
  28050. for (var index = 0; index < camera._rigCameras.length; index++) {
  28051. camera._rigCameras[index].update();
  28052. }
  28053. }
  28054. }
  28055. }
  28056. else if (this.activeCamera) {
  28057. this.activeCamera.update();
  28058. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28059. // rig cameras
  28060. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28061. this.activeCamera._rigCameras[index].update();
  28062. }
  28063. }
  28064. }
  28065. }
  28066. // Before render
  28067. this.onBeforeRenderObservable.notifyObservers(this);
  28068. // Customs render targets
  28069. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28070. var engine = this.getEngine();
  28071. var currentActiveCamera = this.activeCamera;
  28072. if (this.renderTargetsEnabled) {
  28073. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28074. this._intermediateRendering = true;
  28075. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28076. var renderTarget = this.customRenderTargets[customIndex];
  28077. if (renderTarget._shouldRender()) {
  28078. this._renderId++;
  28079. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28080. if (!this.activeCamera)
  28081. throw new Error("Active camera not set");
  28082. // Viewport
  28083. engine.setViewport(this.activeCamera.viewport);
  28084. // Camera
  28085. this.updateTransformMatrix();
  28086. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28087. }
  28088. }
  28089. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28090. this._intermediateRendering = false;
  28091. this._renderId++;
  28092. }
  28093. // Restore back buffer
  28094. if (this.customRenderTargets.length > 0) {
  28095. engine.restoreDefaultFramebuffer();
  28096. }
  28097. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28098. this.activeCamera = currentActiveCamera;
  28099. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28100. var step = _c[_b];
  28101. step.action();
  28102. }
  28103. // Clear
  28104. if (this.autoClearDepthAndStencil || this.autoClear) {
  28105. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28106. }
  28107. // Collects render targets from external components.
  28108. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28109. var step = _e[_d];
  28110. step.action(this._renderTargets);
  28111. }
  28112. // Multi-cameras?
  28113. if (this.activeCameras.length > 0) {
  28114. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28115. if (cameraIndex > 0) {
  28116. this._engine.clear(null, false, true, true);
  28117. }
  28118. this._processSubCameras(this.activeCameras[cameraIndex]);
  28119. }
  28120. }
  28121. else {
  28122. if (!this.activeCamera) {
  28123. throw new Error("No camera defined");
  28124. }
  28125. this._processSubCameras(this.activeCamera);
  28126. }
  28127. // Intersection checks
  28128. this._checkIntersections();
  28129. // Executes the after render stage actions.
  28130. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28131. var step = _g[_f];
  28132. step.action();
  28133. }
  28134. // After render
  28135. if (this.afterRender) {
  28136. this.afterRender();
  28137. }
  28138. this.onAfterRenderObservable.notifyObservers(this);
  28139. // Cleaning
  28140. if (this._toBeDisposed.length) {
  28141. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28142. var data = this._toBeDisposed[index];
  28143. if (data) {
  28144. data.dispose();
  28145. }
  28146. }
  28147. this._toBeDisposed = [];
  28148. }
  28149. if (this.dumpNextRenderTargets) {
  28150. this.dumpNextRenderTargets = false;
  28151. }
  28152. this._activeBones.addCount(0, true);
  28153. this._activeIndices.addCount(0, true);
  28154. this._activeParticles.addCount(0, true);
  28155. };
  28156. /**
  28157. * Freeze all materials
  28158. * A frozen material will not be updatable but should be faster to render
  28159. */
  28160. Scene.prototype.freezeMaterials = function () {
  28161. for (var i = 0; i < this.materials.length; i++) {
  28162. this.materials[i].freeze();
  28163. }
  28164. };
  28165. /**
  28166. * Unfreeze all materials
  28167. * A frozen material will not be updatable but should be faster to render
  28168. */
  28169. Scene.prototype.unfreezeMaterials = function () {
  28170. for (var i = 0; i < this.materials.length; i++) {
  28171. this.materials[i].unfreeze();
  28172. }
  28173. };
  28174. /**
  28175. * Releases all held ressources
  28176. */
  28177. Scene.prototype.dispose = function () {
  28178. this.beforeRender = null;
  28179. this.afterRender = null;
  28180. this.skeletons = [];
  28181. this.morphTargetManagers = [];
  28182. this._transientComponents = [];
  28183. this._isReadyForMeshStage.clear();
  28184. this._beforeEvaluateActiveMeshStage.clear();
  28185. this._evaluateSubMeshStage.clear();
  28186. this._activeMeshStage.clear();
  28187. this._cameraDrawRenderTargetStage.clear();
  28188. this._beforeCameraDrawStage.clear();
  28189. this._beforeRenderingGroupDrawStage.clear();
  28190. this._beforeRenderingMeshStage.clear();
  28191. this._afterRenderingMeshStage.clear();
  28192. this._afterRenderingGroupDrawStage.clear();
  28193. this._afterCameraDrawStage.clear();
  28194. this._afterRenderStage.clear();
  28195. this._beforeCameraUpdateStage.clear();
  28196. this._beforeClearStage.clear();
  28197. this._gatherRenderTargetsStage.clear();
  28198. this._gatherActiveCameraRenderTargetsStage.clear();
  28199. this._pointerMoveStage.clear();
  28200. this._pointerDownStage.clear();
  28201. this._pointerUpStage.clear();
  28202. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28203. var component = _a[_i];
  28204. component.dispose();
  28205. }
  28206. this.importedMeshesFiles = new Array();
  28207. this.stopAllAnimations();
  28208. this.resetCachedMaterial();
  28209. // Smart arrays
  28210. if (this.activeCamera) {
  28211. this.activeCamera._activeMeshes.dispose();
  28212. this.activeCamera = null;
  28213. }
  28214. this._activeMeshes.dispose();
  28215. this._renderingManager.dispose();
  28216. this._processedMaterials.dispose();
  28217. this._activeParticleSystems.dispose();
  28218. this._activeSkeletons.dispose();
  28219. this._softwareSkinnedMeshes.dispose();
  28220. this._renderTargets.dispose();
  28221. this._registeredForLateAnimationBindings.dispose();
  28222. this._meshesForIntersections.dispose();
  28223. this._toBeDisposed = [];
  28224. // Abort active requests
  28225. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28226. var request = _c[_b];
  28227. request.abort();
  28228. }
  28229. // Events
  28230. this.onDisposeObservable.notifyObservers(this);
  28231. this.onDisposeObservable.clear();
  28232. this.onBeforeRenderObservable.clear();
  28233. this.onAfterRenderObservable.clear();
  28234. this.onBeforeRenderTargetsRenderObservable.clear();
  28235. this.onAfterRenderTargetsRenderObservable.clear();
  28236. this.onAfterStepObservable.clear();
  28237. this.onBeforeStepObservable.clear();
  28238. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28239. this.onAfterActiveMeshesEvaluationObservable.clear();
  28240. this.onBeforeParticlesRenderingObservable.clear();
  28241. this.onAfterParticlesRenderingObservable.clear();
  28242. this.onBeforeDrawPhaseObservable.clear();
  28243. this.onAfterDrawPhaseObservable.clear();
  28244. this.onBeforeAnimationsObservable.clear();
  28245. this.onAfterAnimationsObservable.clear();
  28246. this.onDataLoadedObservable.clear();
  28247. this.onBeforeRenderingGroupObservable.clear();
  28248. this.onAfterRenderingGroupObservable.clear();
  28249. this.onMeshImportedObservable.clear();
  28250. this.onBeforeCameraRenderObservable.clear();
  28251. this.onAfterCameraRenderObservable.clear();
  28252. this.onReadyObservable.clear();
  28253. this.onNewCameraAddedObservable.clear();
  28254. this.onCameraRemovedObservable.clear();
  28255. this.onNewLightAddedObservable.clear();
  28256. this.onLightRemovedObservable.clear();
  28257. this.onNewGeometryAddedObservable.clear();
  28258. this.onGeometryRemovedObservable.clear();
  28259. this.onNewTransformNodeAddedObservable.clear();
  28260. this.onTransformNodeRemovedObservable.clear();
  28261. this.onNewMeshAddedObservable.clear();
  28262. this.onMeshRemovedObservable.clear();
  28263. this.onNewMaterialAddedObservable.clear();
  28264. this.onMaterialRemovedObservable.clear();
  28265. this.onNewTextureAddedObservable.clear();
  28266. this.onTextureRemovedObservable.clear();
  28267. this.onPrePointerObservable.clear();
  28268. this.onPointerObservable.clear();
  28269. this.onPreKeyboardObservable.clear();
  28270. this.onKeyboardObservable.clear();
  28271. this.detachControl();
  28272. // Detach cameras
  28273. var canvas = this._engine.getRenderingCanvas();
  28274. if (canvas) {
  28275. var index;
  28276. for (index = 0; index < this.cameras.length; index++) {
  28277. this.cameras[index].detachControl(canvas);
  28278. }
  28279. }
  28280. // Release animation groups
  28281. while (this.animationGroups.length) {
  28282. this.animationGroups[0].dispose();
  28283. }
  28284. // Release lights
  28285. while (this.lights.length) {
  28286. this.lights[0].dispose();
  28287. }
  28288. // Release meshes
  28289. while (this.meshes.length) {
  28290. this.meshes[0].dispose(true);
  28291. }
  28292. while (this.transformNodes.length) {
  28293. this.removeTransformNode(this.transformNodes[0]);
  28294. }
  28295. // Release cameras
  28296. while (this.cameras.length) {
  28297. this.cameras[0].dispose();
  28298. }
  28299. // Release materials
  28300. if (this.defaultMaterial) {
  28301. this.defaultMaterial.dispose();
  28302. }
  28303. while (this.multiMaterials.length) {
  28304. this.multiMaterials[0].dispose();
  28305. }
  28306. while (this.materials.length) {
  28307. this.materials[0].dispose();
  28308. }
  28309. // Release particles
  28310. while (this.particleSystems.length) {
  28311. this.particleSystems[0].dispose();
  28312. }
  28313. // Release postProcesses
  28314. while (this.postProcesses.length) {
  28315. this.postProcesses[0].dispose();
  28316. }
  28317. // Release textures
  28318. while (this.textures.length) {
  28319. this.textures[0].dispose();
  28320. }
  28321. // Release UBO
  28322. this._sceneUbo.dispose();
  28323. if (this._alternateSceneUbo) {
  28324. this._alternateSceneUbo.dispose();
  28325. }
  28326. // Post-processes
  28327. this.postProcessManager.dispose();
  28328. // Remove from engine
  28329. index = this._engine.scenes.indexOf(this);
  28330. if (index > -1) {
  28331. this._engine.scenes.splice(index, 1);
  28332. }
  28333. this._engine.wipeCaches(true);
  28334. this._isDisposed = true;
  28335. };
  28336. Object.defineProperty(Scene.prototype, "isDisposed", {
  28337. /**
  28338. * Gets if the scene is already disposed
  28339. */
  28340. get: function () {
  28341. return this._isDisposed;
  28342. },
  28343. enumerable: true,
  28344. configurable: true
  28345. });
  28346. /**
  28347. * Call this function to reduce memory footprint of the scene.
  28348. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28349. */
  28350. Scene.prototype.clearCachedVertexData = function () {
  28351. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28352. var mesh = this.meshes[meshIndex];
  28353. var geometry = mesh.geometry;
  28354. if (geometry) {
  28355. geometry._indices = [];
  28356. for (var vbName in geometry._vertexBuffers) {
  28357. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28358. continue;
  28359. }
  28360. geometry._vertexBuffers[vbName]._buffer._data = null;
  28361. }
  28362. }
  28363. }
  28364. };
  28365. /**
  28366. * This function will remove the local cached buffer data from texture.
  28367. * It will save memory but will prevent the texture from being rebuilt
  28368. */
  28369. Scene.prototype.cleanCachedTextureBuffer = function () {
  28370. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28371. var baseTexture = _a[_i];
  28372. var buffer = baseTexture._buffer;
  28373. if (buffer) {
  28374. baseTexture._buffer = null;
  28375. }
  28376. }
  28377. };
  28378. /**
  28379. * Get the world extend vectors with an optional filter
  28380. *
  28381. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28382. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28383. */
  28384. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28385. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28386. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28387. filterPredicate = filterPredicate || (function () { return true; });
  28388. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28389. mesh.computeWorldMatrix(true);
  28390. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28391. return;
  28392. }
  28393. var boundingInfo = mesh.getBoundingInfo();
  28394. var minBox = boundingInfo.boundingBox.minimumWorld;
  28395. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28396. BABYLON.Tools.CheckExtends(minBox, min, max);
  28397. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28398. });
  28399. return {
  28400. min: min,
  28401. max: max
  28402. };
  28403. };
  28404. // Picking
  28405. /**
  28406. * Creates a ray that can be used to pick in the scene
  28407. * @param x defines the x coordinate of the origin (on-screen)
  28408. * @param y defines the y coordinate of the origin (on-screen)
  28409. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28410. * @param camera defines the camera to use for the picking
  28411. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28412. * @returns a Ray
  28413. */
  28414. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28415. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28416. var result = BABYLON.Ray.Zero();
  28417. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28418. return result;
  28419. };
  28420. /**
  28421. * Creates a ray that can be used to pick in the scene
  28422. * @param x defines the x coordinate of the origin (on-screen)
  28423. * @param y defines the y coordinate of the origin (on-screen)
  28424. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28425. * @param result defines the ray where to store the picking ray
  28426. * @param camera defines the camera to use for the picking
  28427. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28428. * @returns the current scene
  28429. */
  28430. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28431. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28432. var engine = this._engine;
  28433. if (!camera) {
  28434. if (!this.activeCamera)
  28435. throw new Error("Active camera not set");
  28436. camera = this.activeCamera;
  28437. }
  28438. var cameraViewport = camera.viewport;
  28439. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28440. // Moving coordinates to local viewport world
  28441. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28442. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28443. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28444. return this;
  28445. };
  28446. /**
  28447. * Creates a ray that can be used to pick in the scene
  28448. * @param x defines the x coordinate of the origin (on-screen)
  28449. * @param y defines the y coordinate of the origin (on-screen)
  28450. * @param camera defines the camera to use for the picking
  28451. * @returns a Ray
  28452. */
  28453. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28454. var result = BABYLON.Ray.Zero();
  28455. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28456. return result;
  28457. };
  28458. /**
  28459. * Creates a ray that can be used to pick in the scene
  28460. * @param x defines the x coordinate of the origin (on-screen)
  28461. * @param y defines the y coordinate of the origin (on-screen)
  28462. * @param result defines the ray where to store the picking ray
  28463. * @param camera defines the camera to use for the picking
  28464. * @returns the current scene
  28465. */
  28466. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28467. if (!BABYLON.PickingInfo) {
  28468. return this;
  28469. }
  28470. var engine = this._engine;
  28471. if (!camera) {
  28472. if (!this.activeCamera)
  28473. throw new Error("Active camera not set");
  28474. camera = this.activeCamera;
  28475. }
  28476. var cameraViewport = camera.viewport;
  28477. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28478. var identity = BABYLON.Matrix.Identity();
  28479. // Moving coordinates to local viewport world
  28480. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28481. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28482. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28483. return this;
  28484. };
  28485. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28486. if (!BABYLON.PickingInfo) {
  28487. return null;
  28488. }
  28489. var pickingInfo = null;
  28490. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28491. var mesh = this.meshes[meshIndex];
  28492. if (predicate) {
  28493. if (!predicate(mesh)) {
  28494. continue;
  28495. }
  28496. }
  28497. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28498. continue;
  28499. }
  28500. var world = mesh.getWorldMatrix();
  28501. var ray = rayFunction(world);
  28502. var result = mesh.intersects(ray, fastCheck);
  28503. if (!result || !result.hit)
  28504. continue;
  28505. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28506. continue;
  28507. pickingInfo = result;
  28508. if (fastCheck) {
  28509. break;
  28510. }
  28511. }
  28512. return pickingInfo || new BABYLON.PickingInfo();
  28513. };
  28514. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28515. if (!BABYLON.PickingInfo) {
  28516. return null;
  28517. }
  28518. var pickingInfos = new Array();
  28519. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28520. var mesh = this.meshes[meshIndex];
  28521. if (predicate) {
  28522. if (!predicate(mesh)) {
  28523. continue;
  28524. }
  28525. }
  28526. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28527. continue;
  28528. }
  28529. var world = mesh.getWorldMatrix();
  28530. var ray = rayFunction(world);
  28531. var result = mesh.intersects(ray, false);
  28532. if (!result || !result.hit)
  28533. continue;
  28534. pickingInfos.push(result);
  28535. }
  28536. return pickingInfos;
  28537. };
  28538. /** Launch a ray to try to pick a mesh in the scene
  28539. * @param x position on screen
  28540. * @param y position on screen
  28541. * @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
  28542. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28543. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28544. * @returns a PickingInfo
  28545. */
  28546. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28547. var _this = this;
  28548. if (!BABYLON.PickingInfo) {
  28549. return null;
  28550. }
  28551. var result = this._internalPick(function (world) {
  28552. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28553. return _this._tempPickingRay;
  28554. }, predicate, fastCheck);
  28555. if (result) {
  28556. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28557. }
  28558. return result;
  28559. };
  28560. /** Use the given ray to pick a mesh in the scene
  28561. * @param ray The ray to use to pick meshes
  28562. * @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
  28563. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28564. * @returns a PickingInfo
  28565. */
  28566. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28567. var _this = this;
  28568. var result = this._internalPick(function (world) {
  28569. if (!_this._pickWithRayInverseMatrix) {
  28570. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28571. }
  28572. world.invertToRef(_this._pickWithRayInverseMatrix);
  28573. if (!_this._cachedRayForTransform) {
  28574. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28575. }
  28576. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28577. return _this._cachedRayForTransform;
  28578. }, predicate, fastCheck);
  28579. if (result) {
  28580. result.ray = ray;
  28581. }
  28582. return result;
  28583. };
  28584. /**
  28585. * Launch a ray to try to pick a mesh in the scene
  28586. * @param x X position on screen
  28587. * @param y Y position on screen
  28588. * @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
  28589. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28590. * @returns an array of PickingInfo
  28591. */
  28592. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28593. var _this = this;
  28594. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28595. };
  28596. /**
  28597. * Launch a ray to try to pick a mesh in the scene
  28598. * @param ray Ray to use
  28599. * @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
  28600. * @returns an array of PickingInfo
  28601. */
  28602. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28603. var _this = this;
  28604. return this._internalMultiPick(function (world) {
  28605. if (!_this._pickWithRayInverseMatrix) {
  28606. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28607. }
  28608. world.invertToRef(_this._pickWithRayInverseMatrix);
  28609. if (!_this._cachedRayForTransform) {
  28610. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28611. }
  28612. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28613. return _this._cachedRayForTransform;
  28614. }, predicate);
  28615. };
  28616. /**
  28617. * Force the value of meshUnderPointer
  28618. * @param mesh defines the mesh to use
  28619. */
  28620. Scene.prototype.setPointerOverMesh = function (mesh) {
  28621. if (this._pointerOverMesh === mesh) {
  28622. return;
  28623. }
  28624. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28625. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28626. }
  28627. this._pointerOverMesh = mesh;
  28628. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28629. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28630. }
  28631. };
  28632. /**
  28633. * Gets the mesh under the pointer
  28634. * @returns a Mesh or null if no mesh is under the pointer
  28635. */
  28636. Scene.prototype.getPointerOverMesh = function () {
  28637. return this._pointerOverMesh;
  28638. };
  28639. // Misc.
  28640. /** @hidden */
  28641. Scene.prototype._rebuildGeometries = function () {
  28642. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28643. var geometry = _a[_i];
  28644. geometry._rebuild();
  28645. }
  28646. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28647. var mesh = _c[_b];
  28648. mesh._rebuild();
  28649. }
  28650. if (this.postProcessManager) {
  28651. this.postProcessManager._rebuild();
  28652. }
  28653. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28654. var component = _e[_d];
  28655. component.rebuild();
  28656. }
  28657. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28658. var system = _g[_f];
  28659. system.rebuild();
  28660. }
  28661. };
  28662. /** @hidden */
  28663. Scene.prototype._rebuildTextures = function () {
  28664. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28665. var texture = _a[_i];
  28666. texture._rebuild();
  28667. }
  28668. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28669. };
  28670. // Tags
  28671. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28672. if (tagsQuery === undefined) {
  28673. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28674. return list;
  28675. }
  28676. var listByTags = [];
  28677. forEach = forEach || (function (item) { return; });
  28678. for (var i in list) {
  28679. var item = list[i];
  28680. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28681. listByTags.push(item);
  28682. forEach(item);
  28683. }
  28684. }
  28685. return listByTags;
  28686. };
  28687. /**
  28688. * Get a list of meshes by tags
  28689. * @param tagsQuery defines the tags query to use
  28690. * @param forEach defines a predicate used to filter results
  28691. * @returns an array of Mesh
  28692. */
  28693. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28694. return this._getByTags(this.meshes, tagsQuery, forEach);
  28695. };
  28696. /**
  28697. * Get a list of cameras by tags
  28698. * @param tagsQuery defines the tags query to use
  28699. * @param forEach defines a predicate used to filter results
  28700. * @returns an array of Camera
  28701. */
  28702. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28703. return this._getByTags(this.cameras, tagsQuery, forEach);
  28704. };
  28705. /**
  28706. * Get a list of lights by tags
  28707. * @param tagsQuery defines the tags query to use
  28708. * @param forEach defines a predicate used to filter results
  28709. * @returns an array of Light
  28710. */
  28711. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28712. return this._getByTags(this.lights, tagsQuery, forEach);
  28713. };
  28714. /**
  28715. * Get a list of materials by tags
  28716. * @param tagsQuery defines the tags query to use
  28717. * @param forEach defines a predicate used to filter results
  28718. * @returns an array of Material
  28719. */
  28720. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28721. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28722. };
  28723. /**
  28724. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28725. * This allowed control for front to back rendering or reversly depending of the special needs.
  28726. *
  28727. * @param renderingGroupId The rendering group id corresponding to its index
  28728. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28729. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28730. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28731. */
  28732. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28733. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28734. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28735. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28736. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28737. };
  28738. /**
  28739. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28740. *
  28741. * @param renderingGroupId The rendering group id corresponding to its index
  28742. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28743. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28744. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28745. */
  28746. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28747. if (depth === void 0) { depth = true; }
  28748. if (stencil === void 0) { stencil = true; }
  28749. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28750. };
  28751. /**
  28752. * Gets the current auto clear configuration for one rendering group of the rendering
  28753. * manager.
  28754. * @param index the rendering group index to get the information for
  28755. * @returns The auto clear setup for the requested rendering group
  28756. */
  28757. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28758. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28759. };
  28760. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28761. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28762. get: function () {
  28763. return this._blockMaterialDirtyMechanism;
  28764. },
  28765. set: function (value) {
  28766. if (this._blockMaterialDirtyMechanism === value) {
  28767. return;
  28768. }
  28769. this._blockMaterialDirtyMechanism = value;
  28770. if (!value) { // Do a complete update
  28771. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28772. }
  28773. },
  28774. enumerable: true,
  28775. configurable: true
  28776. });
  28777. /**
  28778. * Will flag all materials as dirty to trigger new shader compilation
  28779. * @param flag defines the flag used to specify which material part must be marked as dirty
  28780. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28781. */
  28782. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28783. if (this._blockMaterialDirtyMechanism) {
  28784. return;
  28785. }
  28786. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28787. var material = _a[_i];
  28788. if (predicate && !predicate(material)) {
  28789. continue;
  28790. }
  28791. material.markAsDirty(flag);
  28792. }
  28793. };
  28794. /** @hidden */
  28795. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28796. var _this = this;
  28797. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28798. this._activeRequests.push(request);
  28799. request.onCompleteObservable.add(function (request) {
  28800. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28801. });
  28802. return request;
  28803. };
  28804. /** @hidden */
  28805. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28806. var _this = this;
  28807. return new Promise(function (resolve, reject) {
  28808. _this._loadFile(url, function (data) {
  28809. resolve(data);
  28810. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28811. reject(exception);
  28812. });
  28813. });
  28814. };
  28815. // Statics
  28816. Scene._uniqueIdCounter = 0;
  28817. /** The fog is deactivated */
  28818. Scene.FOGMODE_NONE = 0;
  28819. /** The fog density is following an exponential function */
  28820. Scene.FOGMODE_EXP = 1;
  28821. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28822. Scene.FOGMODE_EXP2 = 2;
  28823. /** The fog density is following a linear function. */
  28824. Scene.FOGMODE_LINEAR = 3;
  28825. /**
  28826. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28827. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28828. */
  28829. Scene.MinDeltaTime = 1.0;
  28830. /**
  28831. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28832. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28833. */
  28834. Scene.MaxDeltaTime = 1000.0;
  28835. /** The distance in pixel that you have to move to prevent some events */
  28836. Scene.DragMovementThreshold = 10; // in pixels
  28837. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28838. Scene.LongPressDelay = 500; // in milliseconds
  28839. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28840. Scene.DoubleClickDelay = 300; // in milliseconds
  28841. /** If you need to check double click without raising a single click at first click, enable this flag */
  28842. Scene.ExclusiveDoubleClickMode = false;
  28843. return Scene;
  28844. }(BABYLON.AbstractScene));
  28845. BABYLON.Scene = Scene;
  28846. })(BABYLON || (BABYLON = {}));
  28847. //# sourceMappingURL=babylon.scene.js.map
  28848. var BABYLON;
  28849. (function (BABYLON) {
  28850. /**
  28851. * Set of assets to keep when moving a scene into an asset container.
  28852. */
  28853. var KeepAssets = /** @class */ (function (_super) {
  28854. __extends(KeepAssets, _super);
  28855. function KeepAssets() {
  28856. return _super !== null && _super.apply(this, arguments) || this;
  28857. }
  28858. return KeepAssets;
  28859. }(BABYLON.AbstractScene));
  28860. BABYLON.KeepAssets = KeepAssets;
  28861. /**
  28862. * Container with a set of assets that can be added or removed from a scene.
  28863. */
  28864. var AssetContainer = /** @class */ (function (_super) {
  28865. __extends(AssetContainer, _super);
  28866. /**
  28867. * Instantiates an AssetContainer.
  28868. * @param scene The scene the AssetContainer belongs to.
  28869. */
  28870. function AssetContainer(scene) {
  28871. var _this = _super.call(this) || this;
  28872. _this.scene = scene;
  28873. return _this;
  28874. }
  28875. /**
  28876. * Adds all the assets from the container to the scene.
  28877. */
  28878. AssetContainer.prototype.addAllToScene = function () {
  28879. var _this = this;
  28880. this.cameras.forEach(function (o) {
  28881. _this.scene.addCamera(o);
  28882. });
  28883. this.lights.forEach(function (o) {
  28884. _this.scene.addLight(o);
  28885. });
  28886. this.meshes.forEach(function (o) {
  28887. _this.scene.addMesh(o);
  28888. });
  28889. this.skeletons.forEach(function (o) {
  28890. _this.scene.addSkeleton(o);
  28891. });
  28892. this.animations.forEach(function (o) {
  28893. _this.scene.addAnimation(o);
  28894. });
  28895. this.animationGroups.forEach(function (o) {
  28896. _this.scene.addAnimationGroup(o);
  28897. });
  28898. this.multiMaterials.forEach(function (o) {
  28899. _this.scene.addMultiMaterial(o);
  28900. });
  28901. this.materials.forEach(function (o) {
  28902. _this.scene.addMaterial(o);
  28903. });
  28904. this.morphTargetManagers.forEach(function (o) {
  28905. _this.scene.addMorphTargetManager(o);
  28906. });
  28907. this.geometries.forEach(function (o) {
  28908. _this.scene.addGeometry(o);
  28909. });
  28910. this.transformNodes.forEach(function (o) {
  28911. _this.scene.addTransformNode(o);
  28912. });
  28913. this.actionManagers.forEach(function (o) {
  28914. _this.scene.addActionManager(o);
  28915. });
  28916. this.textures.forEach(function (o) {
  28917. _this.scene.addTexture(o);
  28918. });
  28919. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28920. var component = _a[_i];
  28921. component.addFromContainer(this.scene);
  28922. }
  28923. };
  28924. /**
  28925. * Removes all the assets in the container from the scene
  28926. */
  28927. AssetContainer.prototype.removeAllFromScene = function () {
  28928. var _this = this;
  28929. this.cameras.forEach(function (o) {
  28930. _this.scene.removeCamera(o);
  28931. });
  28932. this.lights.forEach(function (o) {
  28933. _this.scene.removeLight(o);
  28934. });
  28935. this.meshes.forEach(function (o) {
  28936. _this.scene.removeMesh(o);
  28937. });
  28938. this.skeletons.forEach(function (o) {
  28939. _this.scene.removeSkeleton(o);
  28940. });
  28941. this.animations.forEach(function (o) {
  28942. _this.scene.removeAnimation(o);
  28943. });
  28944. this.animationGroups.forEach(function (o) {
  28945. _this.scene.removeAnimationGroup(o);
  28946. });
  28947. this.multiMaterials.forEach(function (o) {
  28948. _this.scene.removeMultiMaterial(o);
  28949. });
  28950. this.materials.forEach(function (o) {
  28951. _this.scene.removeMaterial(o);
  28952. });
  28953. this.morphTargetManagers.forEach(function (o) {
  28954. _this.scene.removeMorphTargetManager(o);
  28955. });
  28956. this.geometries.forEach(function (o) {
  28957. _this.scene.removeGeometry(o);
  28958. });
  28959. this.transformNodes.forEach(function (o) {
  28960. _this.scene.removeTransformNode(o);
  28961. });
  28962. this.actionManagers.forEach(function (o) {
  28963. _this.scene.removeActionManager(o);
  28964. });
  28965. this.textures.forEach(function (o) {
  28966. _this.scene.removeTexture(o);
  28967. });
  28968. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28969. var component = _a[_i];
  28970. component.removeFromContainer(this.scene);
  28971. }
  28972. };
  28973. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28974. if (!sourceAssets) {
  28975. return;
  28976. }
  28977. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28978. var asset = sourceAssets_1[_i];
  28979. var move = true;
  28980. if (keepAssets) {
  28981. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28982. var keepAsset = keepAssets_1[_a];
  28983. if (asset === keepAsset) {
  28984. move = false;
  28985. break;
  28986. }
  28987. }
  28988. }
  28989. if (move) {
  28990. targetAssets.push(asset);
  28991. }
  28992. }
  28993. };
  28994. /**
  28995. * Removes all the assets contained in the scene and adds them to the container.
  28996. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28997. */
  28998. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28999. if (keepAssets === undefined) {
  29000. keepAssets = new KeepAssets();
  29001. }
  29002. for (var key in this) {
  29003. if (this.hasOwnProperty(key)) {
  29004. this[key] = this[key] || [];
  29005. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29006. }
  29007. }
  29008. this.removeAllFromScene();
  29009. };
  29010. /**
  29011. * 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.
  29012. * @returns the root mesh
  29013. */
  29014. AssetContainer.prototype.createRootMesh = function () {
  29015. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29016. this.meshes.forEach(function (m) {
  29017. if (!m.parent) {
  29018. rootMesh.addChild(m);
  29019. }
  29020. });
  29021. this.meshes.unshift(rootMesh);
  29022. return rootMesh;
  29023. };
  29024. return AssetContainer;
  29025. }(BABYLON.AbstractScene));
  29026. BABYLON.AssetContainer = AssetContainer;
  29027. })(BABYLON || (BABYLON = {}));
  29028. //# sourceMappingURL=babylon.assetContainer.js.map
  29029. var BABYLON;
  29030. (function (BABYLON) {
  29031. var Buffer = /** @class */ (function () {
  29032. /**
  29033. * Constructor
  29034. * @param engine the engine
  29035. * @param data the data to use for this buffer
  29036. * @param updatable whether the data is updatable
  29037. * @param stride the stride (optional)
  29038. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29039. * @param instanced whether the buffer is instanced (optional)
  29040. * @param useBytes set to true if the stride in in bytes (optional)
  29041. */
  29042. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29043. if (stride === void 0) { stride = 0; }
  29044. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29045. if (instanced === void 0) { instanced = false; }
  29046. if (useBytes === void 0) { useBytes = false; }
  29047. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29048. this._engine = engine.getScene().getEngine();
  29049. }
  29050. else {
  29051. this._engine = engine;
  29052. }
  29053. this._updatable = updatable;
  29054. this._instanced = instanced;
  29055. this._data = data;
  29056. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29057. if (!postponeInternalCreation) { // by default
  29058. this.create();
  29059. }
  29060. }
  29061. /**
  29062. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29063. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29064. * @param offset defines offset in the buffer (0 by default)
  29065. * @param size defines the size in floats of attributes (position is 3 for instance)
  29066. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29067. * @param instanced defines if the vertex buffer contains indexed data
  29068. * @param useBytes defines if the offset and stride are in bytes
  29069. * @returns the new vertex buffer
  29070. */
  29071. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29072. if (useBytes === void 0) { useBytes = false; }
  29073. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29074. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29075. // a lot of these parameters are ignored as they are overriden by the buffer
  29076. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29077. };
  29078. // Properties
  29079. Buffer.prototype.isUpdatable = function () {
  29080. return this._updatable;
  29081. };
  29082. Buffer.prototype.getData = function () {
  29083. return this._data;
  29084. };
  29085. Buffer.prototype.getBuffer = function () {
  29086. return this._buffer;
  29087. };
  29088. /**
  29089. * Gets the stride in float32 units (i.e. byte stride / 4).
  29090. * May not be an integer if the byte stride is not divisible by 4.
  29091. * DEPRECATED. Use byteStride instead.
  29092. * @returns the stride in float32 units
  29093. */
  29094. Buffer.prototype.getStrideSize = function () {
  29095. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29096. };
  29097. // Methods
  29098. Buffer.prototype.create = function (data) {
  29099. if (data === void 0) { data = null; }
  29100. if (!data && this._buffer) {
  29101. return; // nothing to do
  29102. }
  29103. data = data || this._data;
  29104. if (!data) {
  29105. return;
  29106. }
  29107. if (!this._buffer) { // create buffer
  29108. if (this._updatable) {
  29109. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29110. this._data = data;
  29111. }
  29112. else {
  29113. this._buffer = this._engine.createVertexBuffer(data);
  29114. }
  29115. }
  29116. else if (this._updatable) { // update buffer
  29117. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29118. this._data = data;
  29119. }
  29120. };
  29121. /** @hidden */
  29122. Buffer.prototype._rebuild = function () {
  29123. this._buffer = null;
  29124. this.create(this._data);
  29125. };
  29126. Buffer.prototype.update = function (data) {
  29127. this.create(data);
  29128. };
  29129. /**
  29130. * Updates the data directly.
  29131. * @param data the new data
  29132. * @param offset the new offset
  29133. * @param vertexCount the vertex count (optional)
  29134. * @param useBytes set to true if the offset is in bytes
  29135. */
  29136. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29137. if (useBytes === void 0) { useBytes = false; }
  29138. if (!this._buffer) {
  29139. return;
  29140. }
  29141. if (this._updatable) { // update buffer
  29142. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29143. this._data = null;
  29144. }
  29145. };
  29146. Buffer.prototype.dispose = function () {
  29147. if (!this._buffer) {
  29148. return;
  29149. }
  29150. if (this._engine._releaseBuffer(this._buffer)) {
  29151. this._buffer = null;
  29152. }
  29153. };
  29154. return Buffer;
  29155. }());
  29156. BABYLON.Buffer = Buffer;
  29157. })(BABYLON || (BABYLON = {}));
  29158. //# sourceMappingURL=babylon.buffer.js.map
  29159. var BABYLON;
  29160. (function (BABYLON) {
  29161. var VertexBuffer = /** @class */ (function () {
  29162. /**
  29163. * Constructor
  29164. * @param engine the engine
  29165. * @param data the data to use for this vertex buffer
  29166. * @param kind the vertex buffer kind
  29167. * @param updatable whether the data is updatable
  29168. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29169. * @param stride the stride (optional)
  29170. * @param instanced whether the buffer is instanced (optional)
  29171. * @param offset the offset of the data (optional)
  29172. * @param size the number of components (optional)
  29173. * @param type the type of the component (optional)
  29174. * @param normalized whether the data contains normalized data (optional)
  29175. * @param useBytes set to true if stride and offset are in bytes (optional)
  29176. */
  29177. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29178. if (normalized === void 0) { normalized = false; }
  29179. if (useBytes === void 0) { useBytes = false; }
  29180. if (data instanceof BABYLON.Buffer) {
  29181. this._buffer = data;
  29182. this._ownsBuffer = false;
  29183. }
  29184. else {
  29185. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29186. this._ownsBuffer = true;
  29187. }
  29188. this._kind = kind;
  29189. if (type == undefined) {
  29190. var data_1 = this.getData();
  29191. this.type = VertexBuffer.FLOAT;
  29192. if (data_1 instanceof Int8Array)
  29193. this.type = VertexBuffer.BYTE;
  29194. else if (data_1 instanceof Uint8Array)
  29195. this.type = VertexBuffer.UNSIGNED_BYTE;
  29196. else if (data_1 instanceof Int16Array)
  29197. this.type = VertexBuffer.SHORT;
  29198. else if (data_1 instanceof Uint16Array)
  29199. this.type = VertexBuffer.UNSIGNED_SHORT;
  29200. else if (data_1 instanceof Int32Array)
  29201. this.type = VertexBuffer.INT;
  29202. else if (data_1 instanceof Uint32Array)
  29203. this.type = VertexBuffer.UNSIGNED_INT;
  29204. }
  29205. else {
  29206. this.type = type;
  29207. }
  29208. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29209. if (useBytes) {
  29210. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29211. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29212. this.byteOffset = offset || 0;
  29213. }
  29214. else {
  29215. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29216. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29217. this.byteOffset = (offset || 0) * typeByteLength;
  29218. }
  29219. this.normalized = normalized;
  29220. this._instanced = instanced !== undefined ? instanced : false;
  29221. this._instanceDivisor = instanced ? 1 : 0;
  29222. }
  29223. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29224. /**
  29225. * Gets or sets the instance divisor when in instanced mode
  29226. */
  29227. get: function () {
  29228. return this._instanceDivisor;
  29229. },
  29230. set: function (value) {
  29231. this._instanceDivisor = value;
  29232. if (value == 0) {
  29233. this._instanced = false;
  29234. }
  29235. else {
  29236. this._instanced = true;
  29237. }
  29238. },
  29239. enumerable: true,
  29240. configurable: true
  29241. });
  29242. /** @hidden */
  29243. VertexBuffer.prototype._rebuild = function () {
  29244. if (!this._buffer) {
  29245. return;
  29246. }
  29247. this._buffer._rebuild();
  29248. };
  29249. /**
  29250. * Returns the kind of the VertexBuffer (string).
  29251. */
  29252. VertexBuffer.prototype.getKind = function () {
  29253. return this._kind;
  29254. };
  29255. // Properties
  29256. /**
  29257. * Boolean : is the VertexBuffer updatable ?
  29258. */
  29259. VertexBuffer.prototype.isUpdatable = function () {
  29260. return this._buffer.isUpdatable();
  29261. };
  29262. /**
  29263. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29264. */
  29265. VertexBuffer.prototype.getData = function () {
  29266. return this._buffer.getData();
  29267. };
  29268. /**
  29269. * Returns the WebGLBuffer associated to the VertexBuffer.
  29270. */
  29271. VertexBuffer.prototype.getBuffer = function () {
  29272. return this._buffer.getBuffer();
  29273. };
  29274. /**
  29275. * Returns the stride as a multiple of the type byte length.
  29276. * DEPRECATED. Use byteStride instead.
  29277. */
  29278. VertexBuffer.prototype.getStrideSize = function () {
  29279. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29280. };
  29281. /**
  29282. * Returns the offset as a multiple of the type byte length.
  29283. * DEPRECATED. Use byteOffset instead.
  29284. */
  29285. VertexBuffer.prototype.getOffset = function () {
  29286. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29287. };
  29288. /**
  29289. * Returns the number of components per vertex attribute (integer).
  29290. */
  29291. VertexBuffer.prototype.getSize = function () {
  29292. return this._size;
  29293. };
  29294. /**
  29295. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29296. */
  29297. VertexBuffer.prototype.getIsInstanced = function () {
  29298. return this._instanced;
  29299. };
  29300. /**
  29301. * Returns the instancing divisor, zero for non-instanced (integer).
  29302. */
  29303. VertexBuffer.prototype.getInstanceDivisor = function () {
  29304. return this._instanceDivisor;
  29305. };
  29306. // Methods
  29307. /**
  29308. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29309. * Returns the created WebGLBuffer.
  29310. */
  29311. VertexBuffer.prototype.create = function (data) {
  29312. return this._buffer.create(data);
  29313. };
  29314. /**
  29315. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29316. * This function will create a new buffer if the current one is not updatable
  29317. * Returns the updated WebGLBuffer.
  29318. */
  29319. VertexBuffer.prototype.update = function (data) {
  29320. return this._buffer.update(data);
  29321. };
  29322. /**
  29323. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29324. * Returns the directly updated WebGLBuffer.
  29325. * @param data the new data
  29326. * @param offset the new offset
  29327. * @param useBytes set to true if the offset is in bytes
  29328. */
  29329. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29330. if (useBytes === void 0) { useBytes = false; }
  29331. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29332. };
  29333. /**
  29334. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29335. */
  29336. VertexBuffer.prototype.dispose = function () {
  29337. if (this._ownsBuffer) {
  29338. this._buffer.dispose();
  29339. }
  29340. };
  29341. /**
  29342. * Enumerates each value of this vertex buffer as numbers.
  29343. * @param count the number of values to enumerate
  29344. * @param callback the callback function called for each value
  29345. */
  29346. VertexBuffer.prototype.forEach = function (count, callback) {
  29347. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29348. };
  29349. Object.defineProperty(VertexBuffer, "PositionKind", {
  29350. get: function () {
  29351. return VertexBuffer._PositionKind;
  29352. },
  29353. enumerable: true,
  29354. configurable: true
  29355. });
  29356. Object.defineProperty(VertexBuffer, "NormalKind", {
  29357. get: function () {
  29358. return VertexBuffer._NormalKind;
  29359. },
  29360. enumerable: true,
  29361. configurable: true
  29362. });
  29363. Object.defineProperty(VertexBuffer, "TangentKind", {
  29364. get: function () {
  29365. return VertexBuffer._TangentKind;
  29366. },
  29367. enumerable: true,
  29368. configurable: true
  29369. });
  29370. Object.defineProperty(VertexBuffer, "UVKind", {
  29371. get: function () {
  29372. return VertexBuffer._UVKind;
  29373. },
  29374. enumerable: true,
  29375. configurable: true
  29376. });
  29377. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29378. get: function () {
  29379. return VertexBuffer._UV2Kind;
  29380. },
  29381. enumerable: true,
  29382. configurable: true
  29383. });
  29384. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29385. get: function () {
  29386. return VertexBuffer._UV3Kind;
  29387. },
  29388. enumerable: true,
  29389. configurable: true
  29390. });
  29391. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29392. get: function () {
  29393. return VertexBuffer._UV4Kind;
  29394. },
  29395. enumerable: true,
  29396. configurable: true
  29397. });
  29398. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29399. get: function () {
  29400. return VertexBuffer._UV5Kind;
  29401. },
  29402. enumerable: true,
  29403. configurable: true
  29404. });
  29405. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29406. get: function () {
  29407. return VertexBuffer._UV6Kind;
  29408. },
  29409. enumerable: true,
  29410. configurable: true
  29411. });
  29412. Object.defineProperty(VertexBuffer, "ColorKind", {
  29413. get: function () {
  29414. return VertexBuffer._ColorKind;
  29415. },
  29416. enumerable: true,
  29417. configurable: true
  29418. });
  29419. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29420. get: function () {
  29421. return VertexBuffer._MatricesIndicesKind;
  29422. },
  29423. enumerable: true,
  29424. configurable: true
  29425. });
  29426. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29427. get: function () {
  29428. return VertexBuffer._MatricesWeightsKind;
  29429. },
  29430. enumerable: true,
  29431. configurable: true
  29432. });
  29433. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29434. get: function () {
  29435. return VertexBuffer._MatricesIndicesExtraKind;
  29436. },
  29437. enumerable: true,
  29438. configurable: true
  29439. });
  29440. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29441. get: function () {
  29442. return VertexBuffer._MatricesWeightsExtraKind;
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. /**
  29448. * Deduces the stride given a kind.
  29449. * @param kind The kind string to deduce
  29450. * @returns The deduced stride
  29451. */
  29452. VertexBuffer.DeduceStride = function (kind) {
  29453. switch (kind) {
  29454. case VertexBuffer.UVKind:
  29455. case VertexBuffer.UV2Kind:
  29456. case VertexBuffer.UV3Kind:
  29457. case VertexBuffer.UV4Kind:
  29458. case VertexBuffer.UV5Kind:
  29459. case VertexBuffer.UV6Kind:
  29460. return 2;
  29461. case VertexBuffer.NormalKind:
  29462. case VertexBuffer.PositionKind:
  29463. return 3;
  29464. case VertexBuffer.ColorKind:
  29465. case VertexBuffer.MatricesIndicesKind:
  29466. case VertexBuffer.MatricesIndicesExtraKind:
  29467. case VertexBuffer.MatricesWeightsKind:
  29468. case VertexBuffer.MatricesWeightsExtraKind:
  29469. case VertexBuffer.TangentKind:
  29470. return 4;
  29471. default:
  29472. throw new Error("Invalid kind '" + kind + "'");
  29473. }
  29474. };
  29475. /**
  29476. * Gets the byte length of the given type.
  29477. * @param type the type
  29478. * @returns the number of bytes
  29479. */
  29480. VertexBuffer.GetTypeByteLength = function (type) {
  29481. switch (type) {
  29482. case VertexBuffer.BYTE:
  29483. case VertexBuffer.UNSIGNED_BYTE:
  29484. return 1;
  29485. case VertexBuffer.SHORT:
  29486. case VertexBuffer.UNSIGNED_SHORT:
  29487. return 2;
  29488. case VertexBuffer.INT:
  29489. case VertexBuffer.FLOAT:
  29490. return 4;
  29491. default:
  29492. throw new Error("Invalid type '" + type + "'");
  29493. }
  29494. };
  29495. /**
  29496. * Enumerates each value of the given parameters as numbers.
  29497. * @param data the data to enumerate
  29498. * @param byteOffset the byte offset of the data
  29499. * @param byteStride the byte stride of the data
  29500. * @param componentCount the number of components per element
  29501. * @param componentType the type of the component
  29502. * @param count the total number of components
  29503. * @param normalized whether the data is normalized
  29504. * @param callback the callback function called for each value
  29505. */
  29506. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29507. if (data instanceof Array) {
  29508. var offset = byteOffset / 4;
  29509. var stride = byteStride / 4;
  29510. for (var index = 0; index < count; index += componentCount) {
  29511. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29512. callback(data[offset + componentIndex], index + componentIndex);
  29513. }
  29514. offset += stride;
  29515. }
  29516. }
  29517. else {
  29518. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29519. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29520. for (var index = 0; index < count; index += componentCount) {
  29521. var componentByteOffset = byteOffset;
  29522. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29523. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29524. callback(value, index + componentIndex);
  29525. componentByteOffset += componentByteLength;
  29526. }
  29527. byteOffset += byteStride;
  29528. }
  29529. }
  29530. };
  29531. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29532. switch (type) {
  29533. case VertexBuffer.BYTE: {
  29534. var value = dataView.getInt8(byteOffset);
  29535. if (normalized) {
  29536. value = Math.max(value / 127, -1);
  29537. }
  29538. return value;
  29539. }
  29540. case VertexBuffer.UNSIGNED_BYTE: {
  29541. var value = dataView.getUint8(byteOffset);
  29542. if (normalized) {
  29543. value = value / 255;
  29544. }
  29545. return value;
  29546. }
  29547. case VertexBuffer.SHORT: {
  29548. var value = dataView.getInt16(byteOffset, true);
  29549. if (normalized) {
  29550. value = Math.max(value / 16383, -1);
  29551. }
  29552. return value;
  29553. }
  29554. case VertexBuffer.UNSIGNED_SHORT: {
  29555. var value = dataView.getUint16(byteOffset, true);
  29556. if (normalized) {
  29557. value = value / 65535;
  29558. }
  29559. return value;
  29560. }
  29561. case VertexBuffer.FLOAT: {
  29562. return dataView.getFloat32(byteOffset, true);
  29563. }
  29564. default: {
  29565. throw new Error("Invalid component type " + type);
  29566. }
  29567. }
  29568. };
  29569. /**
  29570. * The byte type.
  29571. */
  29572. VertexBuffer.BYTE = 5120;
  29573. /**
  29574. * The unsigned byte type.
  29575. */
  29576. VertexBuffer.UNSIGNED_BYTE = 5121;
  29577. /**
  29578. * The short type.
  29579. */
  29580. VertexBuffer.SHORT = 5122;
  29581. /**
  29582. * The unsigned short type.
  29583. */
  29584. VertexBuffer.UNSIGNED_SHORT = 5123;
  29585. /**
  29586. * The integer type.
  29587. */
  29588. VertexBuffer.INT = 5124;
  29589. /**
  29590. * The unsigned integer type.
  29591. */
  29592. VertexBuffer.UNSIGNED_INT = 5125;
  29593. /**
  29594. * The float type.
  29595. */
  29596. VertexBuffer.FLOAT = 5126;
  29597. // Enums
  29598. VertexBuffer._PositionKind = "position";
  29599. VertexBuffer._NormalKind = "normal";
  29600. VertexBuffer._TangentKind = "tangent";
  29601. VertexBuffer._UVKind = "uv";
  29602. VertexBuffer._UV2Kind = "uv2";
  29603. VertexBuffer._UV3Kind = "uv3";
  29604. VertexBuffer._UV4Kind = "uv4";
  29605. VertexBuffer._UV5Kind = "uv5";
  29606. VertexBuffer._UV6Kind = "uv6";
  29607. VertexBuffer._ColorKind = "color";
  29608. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29609. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29610. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29611. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29612. return VertexBuffer;
  29613. }());
  29614. BABYLON.VertexBuffer = VertexBuffer;
  29615. })(BABYLON || (BABYLON = {}));
  29616. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29617. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29618. var BABYLON;
  29619. (function (BABYLON) {
  29620. /**
  29621. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29622. */
  29623. var DummyInternalTextureTracker = /** @class */ (function () {
  29624. function DummyInternalTextureTracker() {
  29625. /**
  29626. * Gets or set the previous tracker in the list
  29627. */
  29628. this.previous = null;
  29629. /**
  29630. * Gets or set the next tracker in the list
  29631. */
  29632. this.next = null;
  29633. }
  29634. return DummyInternalTextureTracker;
  29635. }());
  29636. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29637. })(BABYLON || (BABYLON = {}));
  29638. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29639. var BABYLON;
  29640. (function (BABYLON) {
  29641. /**
  29642. * Class used to store data associated with WebGL texture data for the engine
  29643. * This class should not be used directly
  29644. */
  29645. var InternalTexture = /** @class */ (function () {
  29646. /**
  29647. * Creates a new InternalTexture
  29648. * @param engine defines the engine to use
  29649. * @param dataSource defines the type of data that will be used
  29650. */
  29651. function InternalTexture(engine, dataSource) {
  29652. /**
  29653. * Observable called when the texture is loaded
  29654. */
  29655. this.onLoadedObservable = new BABYLON.Observable();
  29656. /**
  29657. * Gets or set the previous tracker in the list
  29658. */
  29659. this.previous = null;
  29660. /**
  29661. * Gets or set the next tracker in the list
  29662. */
  29663. this.next = null;
  29664. // Private
  29665. /** @hidden */
  29666. this._initialSlot = -1;
  29667. /** @hidden */
  29668. this._designatedSlot = -1;
  29669. /** @hidden */
  29670. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29671. /** @hidden */
  29672. this._comparisonFunction = 0;
  29673. /** @hidden */
  29674. this._sphericalPolynomial = null;
  29675. /** @hidden */
  29676. this._lodGenerationScale = 0;
  29677. /** @hidden */
  29678. this._lodGenerationOffset = 0;
  29679. /** @hidden */
  29680. this._isRGBD = false;
  29681. /** @hidden */
  29682. this._references = 1;
  29683. this._engine = engine;
  29684. this._dataSource = dataSource;
  29685. this._webGLTexture = engine._createTexture();
  29686. }
  29687. /**
  29688. * Gets the Engine the texture belongs to.
  29689. * @returns The babylon engine
  29690. */
  29691. InternalTexture.prototype.getEngine = function () {
  29692. return this._engine;
  29693. };
  29694. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29695. /**
  29696. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29697. */
  29698. get: function () {
  29699. return this._dataSource;
  29700. },
  29701. enumerable: true,
  29702. configurable: true
  29703. });
  29704. /**
  29705. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29706. */
  29707. InternalTexture.prototype.incrementReferences = function () {
  29708. this._references++;
  29709. };
  29710. /**
  29711. * Change the size of the texture (not the size of the content)
  29712. * @param width defines the new width
  29713. * @param height defines the new height
  29714. * @param depth defines the new depth (1 by default)
  29715. */
  29716. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29717. if (depth === void 0) { depth = 1; }
  29718. this.width = width;
  29719. this.height = height;
  29720. this.depth = depth;
  29721. this.baseWidth = width;
  29722. this.baseHeight = height;
  29723. this.baseDepth = depth;
  29724. this._size = width * height * depth;
  29725. };
  29726. /** @hidden */
  29727. InternalTexture.prototype._rebuild = function () {
  29728. var _this = this;
  29729. var proxy;
  29730. this.isReady = false;
  29731. this._cachedCoordinatesMode = null;
  29732. this._cachedWrapU = null;
  29733. this._cachedWrapV = null;
  29734. this._cachedAnisotropicFilteringLevel = null;
  29735. switch (this._dataSource) {
  29736. case InternalTexture.DATASOURCE_TEMP:
  29737. return;
  29738. case InternalTexture.DATASOURCE_URL:
  29739. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29740. _this.isReady = true;
  29741. }, null, this._buffer, undefined, this.format);
  29742. proxy._swapAndDie(this);
  29743. return;
  29744. case InternalTexture.DATASOURCE_RAW:
  29745. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29746. proxy._swapAndDie(this);
  29747. this.isReady = true;
  29748. return;
  29749. case InternalTexture.DATASOURCE_RAW3D:
  29750. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29751. proxy._swapAndDie(this);
  29752. this.isReady = true;
  29753. return;
  29754. case InternalTexture.DATASOURCE_DYNAMIC:
  29755. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29756. proxy._swapAndDie(this);
  29757. // The engine will make sure to update content so no need to flag it as isReady = true
  29758. return;
  29759. case InternalTexture.DATASOURCE_RENDERTARGET:
  29760. var options = new BABYLON.RenderTargetCreationOptions();
  29761. options.generateDepthBuffer = this._generateDepthBuffer;
  29762. options.generateMipMaps = this.generateMipMaps;
  29763. options.generateStencilBuffer = this._generateStencilBuffer;
  29764. options.samplingMode = this.samplingMode;
  29765. options.type = this.type;
  29766. if (this.isCube) {
  29767. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29768. }
  29769. else {
  29770. var size = {
  29771. width: this.width,
  29772. height: this.height
  29773. };
  29774. proxy = this._engine.createRenderTargetTexture(size, options);
  29775. }
  29776. proxy._swapAndDie(this);
  29777. this.isReady = true;
  29778. return;
  29779. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29780. var depthTextureOptions = {
  29781. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29782. comparisonFunction: this._comparisonFunction,
  29783. generateStencil: this._generateStencilBuffer,
  29784. isCube: this.isCube
  29785. };
  29786. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29787. proxy._swapAndDie(this);
  29788. this.isReady = true;
  29789. return;
  29790. case InternalTexture.DATASOURCE_CUBE:
  29791. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29792. _this.isReady = true;
  29793. }, null, this.format, this._extension);
  29794. proxy._swapAndDie(this);
  29795. return;
  29796. case InternalTexture.DATASOURCE_CUBERAW:
  29797. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29798. proxy._swapAndDie(this);
  29799. this.isReady = true;
  29800. return;
  29801. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29802. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29803. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29804. _this.isReady = true;
  29805. });
  29806. proxy._swapAndDie(this);
  29807. return;
  29808. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29809. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29810. if (proxy) {
  29811. proxy._swapAndDie(_this);
  29812. }
  29813. _this.isReady = true;
  29814. }, null, this.format, this._extension);
  29815. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29816. return;
  29817. }
  29818. };
  29819. /** @hidden */
  29820. InternalTexture.prototype._swapAndDie = function (target) {
  29821. target._webGLTexture = this._webGLTexture;
  29822. if (this._framebuffer) {
  29823. target._framebuffer = this._framebuffer;
  29824. }
  29825. if (this._depthStencilBuffer) {
  29826. target._depthStencilBuffer = this._depthStencilBuffer;
  29827. }
  29828. if (this._lodTextureHigh) {
  29829. if (target._lodTextureHigh) {
  29830. target._lodTextureHigh.dispose();
  29831. }
  29832. target._lodTextureHigh = this._lodTextureHigh;
  29833. }
  29834. if (this._lodTextureMid) {
  29835. if (target._lodTextureMid) {
  29836. target._lodTextureMid.dispose();
  29837. }
  29838. target._lodTextureMid = this._lodTextureMid;
  29839. }
  29840. if (this._lodTextureLow) {
  29841. if (target._lodTextureLow) {
  29842. target._lodTextureLow.dispose();
  29843. }
  29844. target._lodTextureLow = this._lodTextureLow;
  29845. }
  29846. var cache = this._engine.getLoadedTexturesCache();
  29847. var index = cache.indexOf(this);
  29848. if (index !== -1) {
  29849. cache.splice(index, 1);
  29850. }
  29851. };
  29852. /**
  29853. * Dispose the current allocated resources
  29854. */
  29855. InternalTexture.prototype.dispose = function () {
  29856. if (!this._webGLTexture) {
  29857. return;
  29858. }
  29859. this._references--;
  29860. if (this._references === 0) {
  29861. this._engine._releaseTexture(this);
  29862. this._webGLTexture = null;
  29863. this.previous = null;
  29864. this.next = null;
  29865. }
  29866. };
  29867. /**
  29868. * The source of the texture data is unknown
  29869. */
  29870. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29871. /**
  29872. * Texture data comes from an URL
  29873. */
  29874. InternalTexture.DATASOURCE_URL = 1;
  29875. /**
  29876. * Texture data is only used for temporary storage
  29877. */
  29878. InternalTexture.DATASOURCE_TEMP = 2;
  29879. /**
  29880. * Texture data comes from raw data (ArrayBuffer)
  29881. */
  29882. InternalTexture.DATASOURCE_RAW = 3;
  29883. /**
  29884. * Texture content is dynamic (video or dynamic texture)
  29885. */
  29886. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29887. /**
  29888. * Texture content is generated by rendering to it
  29889. */
  29890. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29891. /**
  29892. * Texture content is part of a multi render target process
  29893. */
  29894. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29895. /**
  29896. * Texture data comes from a cube data file
  29897. */
  29898. InternalTexture.DATASOURCE_CUBE = 7;
  29899. /**
  29900. * Texture data comes from a raw cube data
  29901. */
  29902. InternalTexture.DATASOURCE_CUBERAW = 8;
  29903. /**
  29904. * Texture data come from a prefiltered cube data file
  29905. */
  29906. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29907. /**
  29908. * Texture content is raw 3D data
  29909. */
  29910. InternalTexture.DATASOURCE_RAW3D = 10;
  29911. /**
  29912. * Texture content is a depth texture
  29913. */
  29914. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29915. /**
  29916. * Texture data comes from a raw cube data encoded with RGBD
  29917. */
  29918. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29919. return InternalTexture;
  29920. }());
  29921. BABYLON.InternalTexture = InternalTexture;
  29922. })(BABYLON || (BABYLON = {}));
  29923. //# sourceMappingURL=babylon.internalTexture.js.map
  29924. var BABYLON;
  29925. (function (BABYLON) {
  29926. var BaseTexture = /** @class */ (function () {
  29927. function BaseTexture(scene) {
  29928. this._hasAlpha = false;
  29929. this.getAlphaFromRGB = false;
  29930. this.level = 1;
  29931. this.coordinatesIndex = 0;
  29932. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29933. /**
  29934. * | Value | Type | Description |
  29935. * | ----- | ------------------ | ----------- |
  29936. * | 0 | CLAMP_ADDRESSMODE | |
  29937. * | 1 | WRAP_ADDRESSMODE | |
  29938. * | 2 | MIRROR_ADDRESSMODE | |
  29939. */
  29940. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29941. /**
  29942. * | Value | Type | Description |
  29943. * | ----- | ------------------ | ----------- |
  29944. * | 0 | CLAMP_ADDRESSMODE | |
  29945. * | 1 | WRAP_ADDRESSMODE | |
  29946. * | 2 | MIRROR_ADDRESSMODE | |
  29947. */
  29948. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29949. /**
  29950. * | Value | Type | Description |
  29951. * | ----- | ------------------ | ----------- |
  29952. * | 0 | CLAMP_ADDRESSMODE | |
  29953. * | 1 | WRAP_ADDRESSMODE | |
  29954. * | 2 | MIRROR_ADDRESSMODE | |
  29955. */
  29956. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29957. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29958. this.isCube = false;
  29959. this.is3D = false;
  29960. this.gammaSpace = true;
  29961. this.invertZ = false;
  29962. this.lodLevelInAlpha = false;
  29963. this.isRenderTarget = false;
  29964. this.animations = new Array();
  29965. /**
  29966. * An event triggered when the texture is disposed.
  29967. */
  29968. this.onDisposeObservable = new BABYLON.Observable();
  29969. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29970. this._cachedSize = BABYLON.Size.Zero();
  29971. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29972. if (this._scene) {
  29973. this._scene.textures.push(this);
  29974. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  29975. }
  29976. this._uid = null;
  29977. }
  29978. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29979. get: function () {
  29980. return this._hasAlpha;
  29981. },
  29982. set: function (value) {
  29983. if (this._hasAlpha === value) {
  29984. return;
  29985. }
  29986. this._hasAlpha = value;
  29987. if (this._scene) {
  29988. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29989. }
  29990. },
  29991. enumerable: true,
  29992. configurable: true
  29993. });
  29994. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29995. get: function () {
  29996. return this._coordinatesMode;
  29997. },
  29998. /**
  29999. * How a texture is mapped.
  30000. *
  30001. * | Value | Type | Description |
  30002. * | ----- | ----------------------------------- | ----------- |
  30003. * | 0 | EXPLICIT_MODE | |
  30004. * | 1 | SPHERICAL_MODE | |
  30005. * | 2 | PLANAR_MODE | |
  30006. * | 3 | CUBIC_MODE | |
  30007. * | 4 | PROJECTION_MODE | |
  30008. * | 5 | SKYBOX_MODE | |
  30009. * | 6 | INVCUBIC_MODE | |
  30010. * | 7 | EQUIRECTANGULAR_MODE | |
  30011. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30012. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30013. */
  30014. set: function (value) {
  30015. if (this._coordinatesMode === value) {
  30016. return;
  30017. }
  30018. this._coordinatesMode = value;
  30019. if (this._scene) {
  30020. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30021. }
  30022. },
  30023. enumerable: true,
  30024. configurable: true
  30025. });
  30026. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30027. /**
  30028. * Gets whether or not the texture contains RGBD data.
  30029. */
  30030. get: function () {
  30031. return this._texture != null && this._texture._isRGBD;
  30032. },
  30033. enumerable: true,
  30034. configurable: true
  30035. });
  30036. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30037. get: function () {
  30038. if (this._texture)
  30039. return this._texture._lodGenerationOffset;
  30040. return 0.0;
  30041. },
  30042. set: function (value) {
  30043. if (this._texture)
  30044. this._texture._lodGenerationOffset = value;
  30045. },
  30046. enumerable: true,
  30047. configurable: true
  30048. });
  30049. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30050. get: function () {
  30051. if (this._texture)
  30052. return this._texture._lodGenerationScale;
  30053. return 0.0;
  30054. },
  30055. set: function (value) {
  30056. if (this._texture)
  30057. this._texture._lodGenerationScale = value;
  30058. },
  30059. enumerable: true,
  30060. configurable: true
  30061. });
  30062. Object.defineProperty(BaseTexture.prototype, "uid", {
  30063. get: function () {
  30064. if (!this._uid) {
  30065. this._uid = BABYLON.Tools.RandomId();
  30066. }
  30067. return this._uid;
  30068. },
  30069. enumerable: true,
  30070. configurable: true
  30071. });
  30072. BaseTexture.prototype.toString = function () {
  30073. return this.name;
  30074. };
  30075. BaseTexture.prototype.getClassName = function () {
  30076. return "BaseTexture";
  30077. };
  30078. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30079. set: function (callback) {
  30080. if (this._onDisposeObserver) {
  30081. this.onDisposeObservable.remove(this._onDisposeObserver);
  30082. }
  30083. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30084. },
  30085. enumerable: true,
  30086. configurable: true
  30087. });
  30088. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30089. get: function () {
  30090. return true;
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. BaseTexture.prototype.getScene = function () {
  30096. return this._scene;
  30097. };
  30098. BaseTexture.prototype.getTextureMatrix = function () {
  30099. return BABYLON.Matrix.IdentityReadOnly;
  30100. };
  30101. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30102. return BABYLON.Matrix.IdentityReadOnly;
  30103. };
  30104. BaseTexture.prototype.getInternalTexture = function () {
  30105. return this._texture;
  30106. };
  30107. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30108. return !this.isBlocking || this.isReady();
  30109. };
  30110. BaseTexture.prototype.isReady = function () {
  30111. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30112. this.delayLoad();
  30113. return false;
  30114. }
  30115. if (this._texture) {
  30116. return this._texture.isReady;
  30117. }
  30118. return false;
  30119. };
  30120. BaseTexture.prototype.getSize = function () {
  30121. if (this._texture) {
  30122. if (this._texture.width) {
  30123. this._cachedSize.width = this._texture.width;
  30124. this._cachedSize.height = this._texture.height;
  30125. return this._cachedSize;
  30126. }
  30127. if (this._texture._size) {
  30128. this._cachedSize.width = this._texture._size;
  30129. this._cachedSize.height = this._texture._size;
  30130. return this._cachedSize;
  30131. }
  30132. }
  30133. return this._cachedSize;
  30134. };
  30135. BaseTexture.prototype.getBaseSize = function () {
  30136. if (!this.isReady() || !this._texture)
  30137. return BABYLON.Size.Zero();
  30138. if (this._texture._size) {
  30139. return new BABYLON.Size(this._texture._size, this._texture._size);
  30140. }
  30141. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30142. };
  30143. BaseTexture.prototype.scale = function (ratio) {
  30144. };
  30145. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30146. get: function () {
  30147. return false;
  30148. },
  30149. enumerable: true,
  30150. configurable: true
  30151. });
  30152. /** @hidden */
  30153. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30154. if (!this._scene) {
  30155. return null;
  30156. }
  30157. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30158. for (var index = 0; index < texturesCache.length; index++) {
  30159. var texturesCacheEntry = texturesCache[index];
  30160. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30161. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30162. texturesCacheEntry.incrementReferences();
  30163. return texturesCacheEntry;
  30164. }
  30165. }
  30166. }
  30167. return null;
  30168. };
  30169. /** @hidden */
  30170. BaseTexture.prototype._rebuild = function () {
  30171. };
  30172. BaseTexture.prototype.delayLoad = function () {
  30173. };
  30174. BaseTexture.prototype.clone = function () {
  30175. return null;
  30176. };
  30177. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30178. get: function () {
  30179. if (!this._texture) {
  30180. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30181. }
  30182. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30183. },
  30184. enumerable: true,
  30185. configurable: true
  30186. });
  30187. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30188. get: function () {
  30189. if (!this._texture) {
  30190. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30191. }
  30192. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30193. },
  30194. enumerable: true,
  30195. configurable: true
  30196. });
  30197. /**
  30198. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30199. * This will returns an RGBA array buffer containing either in values (0-255) or
  30200. * float values (0-1) depending of the underlying buffer type.
  30201. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30202. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30203. * @param buffer defines a user defined buffer to fill with data (can be null)
  30204. * @returns The Array buffer containing the pixels data.
  30205. */
  30206. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30207. if (faceIndex === void 0) { faceIndex = 0; }
  30208. if (level === void 0) { level = 0; }
  30209. if (buffer === void 0) { buffer = null; }
  30210. if (!this._texture) {
  30211. return null;
  30212. }
  30213. var size = this.getSize();
  30214. var width = size.width;
  30215. var height = size.height;
  30216. var scene = this.getScene();
  30217. if (!scene) {
  30218. return null;
  30219. }
  30220. var engine = scene.getEngine();
  30221. if (level != 0) {
  30222. width = width / Math.pow(2, level);
  30223. height = height / Math.pow(2, level);
  30224. width = Math.round(width);
  30225. height = Math.round(height);
  30226. }
  30227. if (this._texture.isCube) {
  30228. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30229. }
  30230. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30231. };
  30232. BaseTexture.prototype.releaseInternalTexture = function () {
  30233. if (this._texture) {
  30234. this._texture.dispose();
  30235. this._texture = null;
  30236. }
  30237. };
  30238. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30239. get: function () {
  30240. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30241. return null;
  30242. }
  30243. if (!this._texture._sphericalPolynomial) {
  30244. this._texture._sphericalPolynomial =
  30245. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30246. }
  30247. return this._texture._sphericalPolynomial;
  30248. },
  30249. set: function (value) {
  30250. if (this._texture) {
  30251. this._texture._sphericalPolynomial = value;
  30252. }
  30253. },
  30254. enumerable: true,
  30255. configurable: true
  30256. });
  30257. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30258. get: function () {
  30259. if (this._texture) {
  30260. return this._texture._lodTextureHigh;
  30261. }
  30262. return null;
  30263. },
  30264. enumerable: true,
  30265. configurable: true
  30266. });
  30267. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30268. get: function () {
  30269. if (this._texture) {
  30270. return this._texture._lodTextureMid;
  30271. }
  30272. return null;
  30273. },
  30274. enumerable: true,
  30275. configurable: true
  30276. });
  30277. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30278. get: function () {
  30279. if (this._texture) {
  30280. return this._texture._lodTextureLow;
  30281. }
  30282. return null;
  30283. },
  30284. enumerable: true,
  30285. configurable: true
  30286. });
  30287. BaseTexture.prototype.dispose = function () {
  30288. if (!this._scene) {
  30289. return;
  30290. }
  30291. // Animations
  30292. this._scene.stopAnimation(this);
  30293. // Remove from scene
  30294. this._scene._removePendingData(this);
  30295. var index = this._scene.textures.indexOf(this);
  30296. if (index >= 0) {
  30297. this._scene.textures.splice(index, 1);
  30298. }
  30299. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30300. if (this._texture === undefined) {
  30301. return;
  30302. }
  30303. // Release
  30304. this.releaseInternalTexture();
  30305. // Callback
  30306. this.onDisposeObservable.notifyObservers(this);
  30307. this.onDisposeObservable.clear();
  30308. };
  30309. BaseTexture.prototype.serialize = function () {
  30310. if (!this.name) {
  30311. return null;
  30312. }
  30313. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30314. // Animations
  30315. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30316. return serializationObject;
  30317. };
  30318. BaseTexture.WhenAllReady = function (textures, callback) {
  30319. var numRemaining = textures.length;
  30320. if (numRemaining === 0) {
  30321. callback();
  30322. return;
  30323. }
  30324. var _loop_1 = function () {
  30325. texture = textures[i];
  30326. if (texture.isReady()) {
  30327. if (--numRemaining === 0) {
  30328. callback();
  30329. }
  30330. }
  30331. else {
  30332. onLoadObservable = texture.onLoadObservable;
  30333. var onLoadCallback_1 = function () {
  30334. onLoadObservable.removeCallback(onLoadCallback_1);
  30335. if (--numRemaining === 0) {
  30336. callback();
  30337. }
  30338. };
  30339. onLoadObservable.add(onLoadCallback_1);
  30340. }
  30341. };
  30342. var texture, onLoadObservable;
  30343. for (var i = 0; i < textures.length; i++) {
  30344. _loop_1();
  30345. }
  30346. };
  30347. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30348. __decorate([
  30349. BABYLON.serialize()
  30350. ], BaseTexture.prototype, "name", void 0);
  30351. __decorate([
  30352. BABYLON.serialize("hasAlpha")
  30353. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30354. __decorate([
  30355. BABYLON.serialize()
  30356. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30357. __decorate([
  30358. BABYLON.serialize()
  30359. ], BaseTexture.prototype, "level", void 0);
  30360. __decorate([
  30361. BABYLON.serialize()
  30362. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30363. __decorate([
  30364. BABYLON.serialize("coordinatesMode")
  30365. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30366. __decorate([
  30367. BABYLON.serialize()
  30368. ], BaseTexture.prototype, "wrapU", void 0);
  30369. __decorate([
  30370. BABYLON.serialize()
  30371. ], BaseTexture.prototype, "wrapV", void 0);
  30372. __decorate([
  30373. BABYLON.serialize()
  30374. ], BaseTexture.prototype, "wrapR", void 0);
  30375. __decorate([
  30376. BABYLON.serialize()
  30377. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30378. __decorate([
  30379. BABYLON.serialize()
  30380. ], BaseTexture.prototype, "isCube", void 0);
  30381. __decorate([
  30382. BABYLON.serialize()
  30383. ], BaseTexture.prototype, "is3D", void 0);
  30384. __decorate([
  30385. BABYLON.serialize()
  30386. ], BaseTexture.prototype, "gammaSpace", void 0);
  30387. __decorate([
  30388. BABYLON.serialize()
  30389. ], BaseTexture.prototype, "invertZ", void 0);
  30390. __decorate([
  30391. BABYLON.serialize()
  30392. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30393. __decorate([
  30394. BABYLON.serialize()
  30395. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30396. __decorate([
  30397. BABYLON.serialize()
  30398. ], BaseTexture.prototype, "lodGenerationScale", null);
  30399. __decorate([
  30400. BABYLON.serialize()
  30401. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30402. return BaseTexture;
  30403. }());
  30404. BABYLON.BaseTexture = BaseTexture;
  30405. })(BABYLON || (BABYLON = {}));
  30406. //# sourceMappingURL=babylon.baseTexture.js.map
  30407. var BABYLON;
  30408. (function (BABYLON) {
  30409. var Texture = /** @class */ (function (_super) {
  30410. __extends(Texture, _super);
  30411. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30412. if (noMipmap === void 0) { noMipmap = false; }
  30413. if (invertY === void 0) { invertY = true; }
  30414. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30415. if (onLoad === void 0) { onLoad = null; }
  30416. if (onError === void 0) { onError = null; }
  30417. if (buffer === void 0) { buffer = null; }
  30418. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30419. var _this = _super.call(this, scene) || this;
  30420. _this.uOffset = 0;
  30421. _this.vOffset = 0;
  30422. _this.uScale = 1.0;
  30423. _this.vScale = 1.0;
  30424. _this.uAng = 0;
  30425. _this.vAng = 0;
  30426. _this.wAng = 0;
  30427. /**
  30428. * Defines the center of rotation (U)
  30429. */
  30430. _this.uRotationCenter = 0.5;
  30431. /**
  30432. * Defines the center of rotation (V)
  30433. */
  30434. _this.vRotationCenter = 0.5;
  30435. /**
  30436. * Defines the center of rotation (W)
  30437. */
  30438. _this.wRotationCenter = 0.5;
  30439. _this._isBlocking = true;
  30440. _this.name = url || "";
  30441. _this.url = url;
  30442. _this._noMipmap = noMipmap;
  30443. _this._invertY = invertY;
  30444. _this._samplingMode = samplingMode;
  30445. _this._buffer = buffer;
  30446. _this._deleteBuffer = deleteBuffer;
  30447. if (format) {
  30448. _this._format = format;
  30449. }
  30450. scene = _this.getScene();
  30451. if (!scene) {
  30452. return _this;
  30453. }
  30454. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30455. var load = function () {
  30456. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30457. _this.onLoadObservable.notifyObservers(_this);
  30458. }
  30459. if (onLoad) {
  30460. onLoad();
  30461. }
  30462. if (!_this.isBlocking && scene) {
  30463. scene.resetCachedMaterial();
  30464. }
  30465. };
  30466. if (!_this.url) {
  30467. _this._delayedOnLoad = load;
  30468. _this._delayedOnError = onError;
  30469. return _this;
  30470. }
  30471. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30472. if (!_this._texture) {
  30473. if (!scene.useDelayedTextureLoading) {
  30474. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30475. if (deleteBuffer) {
  30476. delete _this._buffer;
  30477. }
  30478. }
  30479. else {
  30480. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30481. _this._delayedOnLoad = load;
  30482. _this._delayedOnError = onError;
  30483. }
  30484. }
  30485. else {
  30486. if (_this._texture.isReady) {
  30487. BABYLON.Tools.SetImmediate(function () { return load(); });
  30488. }
  30489. else {
  30490. _this._texture.onLoadedObservable.add(load);
  30491. }
  30492. }
  30493. return _this;
  30494. }
  30495. Object.defineProperty(Texture.prototype, "noMipmap", {
  30496. get: function () {
  30497. return this._noMipmap;
  30498. },
  30499. enumerable: true,
  30500. configurable: true
  30501. });
  30502. Object.defineProperty(Texture.prototype, "isBlocking", {
  30503. get: function () {
  30504. return this._isBlocking;
  30505. },
  30506. set: function (value) {
  30507. this._isBlocking = value;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. Object.defineProperty(Texture.prototype, "samplingMode", {
  30513. get: function () {
  30514. return this._samplingMode;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. /**
  30520. * Update the url (and optional buffer) of this texture if url was null during construction.
  30521. * @param url the url of the texture
  30522. * @param buffer the buffer of the texture (defaults to null)
  30523. */
  30524. Texture.prototype.updateURL = function (url, buffer) {
  30525. if (buffer === void 0) { buffer = null; }
  30526. if (this.url) {
  30527. throw new Error("URL is already set");
  30528. }
  30529. this.url = url;
  30530. this._buffer = buffer;
  30531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30532. this.delayLoad();
  30533. };
  30534. Texture.prototype.delayLoad = function () {
  30535. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30536. return;
  30537. }
  30538. var scene = this.getScene();
  30539. if (!scene) {
  30540. return;
  30541. }
  30542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30543. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30544. if (!this._texture) {
  30545. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30546. if (this._deleteBuffer) {
  30547. delete this._buffer;
  30548. }
  30549. }
  30550. else {
  30551. if (this._delayedOnLoad) {
  30552. if (this._texture.isReady) {
  30553. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30554. }
  30555. else {
  30556. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30557. }
  30558. }
  30559. }
  30560. this._delayedOnLoad = null;
  30561. this._delayedOnError = null;
  30562. };
  30563. /**
  30564. * Default is Trilinear mode.
  30565. *
  30566. * | Value | Type | Description |
  30567. * | ----- | ------------------ | ----------- |
  30568. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30569. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30570. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30571. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30572. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30573. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30574. * | 7 | NEAREST_LINEAR | |
  30575. * | 8 | NEAREST_NEAREST | |
  30576. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30577. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30578. * | 11 | LINEAR_LINEAR | |
  30579. * | 12 | LINEAR_NEAREST | |
  30580. *
  30581. * > _mag_: magnification filter (close to the viewer)
  30582. * > _min_: minification filter (far from the viewer)
  30583. * > _mip_: filter used between mip map levels
  30584. *
  30585. */
  30586. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30587. if (!this._texture) {
  30588. return;
  30589. }
  30590. var scene = this.getScene();
  30591. if (!scene) {
  30592. return;
  30593. }
  30594. this._samplingMode = samplingMode;
  30595. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30596. };
  30597. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30598. x *= this.uScale;
  30599. y *= this.vScale;
  30600. x -= this.uRotationCenter * this.uScale;
  30601. y -= this.vRotationCenter * this.vScale;
  30602. z -= this.wRotationCenter;
  30603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30604. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30605. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30606. t.z += this.wRotationCenter;
  30607. };
  30608. Texture.prototype.getTextureMatrix = function () {
  30609. var _this = this;
  30610. if (this.uOffset === this._cachedUOffset &&
  30611. this.vOffset === this._cachedVOffset &&
  30612. this.uScale === this._cachedUScale &&
  30613. this.vScale === this._cachedVScale &&
  30614. this.uAng === this._cachedUAng &&
  30615. this.vAng === this._cachedVAng &&
  30616. this.wAng === this._cachedWAng) {
  30617. return this._cachedTextureMatrix;
  30618. }
  30619. this._cachedUOffset = this.uOffset;
  30620. this._cachedVOffset = this.vOffset;
  30621. this._cachedUScale = this.uScale;
  30622. this._cachedVScale = this.vScale;
  30623. this._cachedUAng = this.uAng;
  30624. this._cachedVAng = this.vAng;
  30625. this._cachedWAng = this.wAng;
  30626. if (!this._cachedTextureMatrix) {
  30627. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30628. this._rowGenerationMatrix = new BABYLON.Matrix();
  30629. this._t0 = BABYLON.Vector3.Zero();
  30630. this._t1 = BABYLON.Vector3.Zero();
  30631. this._t2 = BABYLON.Vector3.Zero();
  30632. }
  30633. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30634. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30635. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30636. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30637. this._t1.subtractInPlace(this._t0);
  30638. this._t2.subtractInPlace(this._t0);
  30639. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30640. this._cachedTextureMatrix.m[0] = this._t1.x;
  30641. this._cachedTextureMatrix.m[1] = this._t1.y;
  30642. this._cachedTextureMatrix.m[2] = this._t1.z;
  30643. this._cachedTextureMatrix.m[4] = this._t2.x;
  30644. this._cachedTextureMatrix.m[5] = this._t2.y;
  30645. this._cachedTextureMatrix.m[6] = this._t2.z;
  30646. this._cachedTextureMatrix.m[8] = this._t0.x;
  30647. this._cachedTextureMatrix.m[9] = this._t0.y;
  30648. this._cachedTextureMatrix.m[10] = this._t0.z;
  30649. var scene = this.getScene();
  30650. if (!scene) {
  30651. return this._cachedTextureMatrix;
  30652. }
  30653. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30654. return mat.hasTexture(_this);
  30655. });
  30656. return this._cachedTextureMatrix;
  30657. };
  30658. Texture.prototype.getReflectionTextureMatrix = function () {
  30659. var _this = this;
  30660. var scene = this.getScene();
  30661. if (!scene) {
  30662. return this._cachedTextureMatrix;
  30663. }
  30664. if (this.uOffset === this._cachedUOffset &&
  30665. this.vOffset === this._cachedVOffset &&
  30666. this.uScale === this._cachedUScale &&
  30667. this.vScale === this._cachedVScale &&
  30668. this.coordinatesMode === this._cachedCoordinatesMode) {
  30669. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30670. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30671. return this._cachedTextureMatrix;
  30672. }
  30673. }
  30674. else {
  30675. return this._cachedTextureMatrix;
  30676. }
  30677. }
  30678. if (!this._cachedTextureMatrix) {
  30679. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30680. }
  30681. if (!this._projectionModeMatrix) {
  30682. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30683. }
  30684. this._cachedUOffset = this.uOffset;
  30685. this._cachedVOffset = this.vOffset;
  30686. this._cachedUScale = this.uScale;
  30687. this._cachedVScale = this.vScale;
  30688. this._cachedCoordinatesMode = this.coordinatesMode;
  30689. switch (this.coordinatesMode) {
  30690. case Texture.PLANAR_MODE:
  30691. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30692. this._cachedTextureMatrix[0] = this.uScale;
  30693. this._cachedTextureMatrix[5] = this.vScale;
  30694. this._cachedTextureMatrix[12] = this.uOffset;
  30695. this._cachedTextureMatrix[13] = this.vOffset;
  30696. break;
  30697. case Texture.PROJECTION_MODE:
  30698. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30699. this._projectionModeMatrix.m[0] = 0.5;
  30700. this._projectionModeMatrix.m[5] = -0.5;
  30701. this._projectionModeMatrix.m[10] = 0.0;
  30702. this._projectionModeMatrix.m[12] = 0.5;
  30703. this._projectionModeMatrix.m[13] = 0.5;
  30704. this._projectionModeMatrix.m[14] = 1.0;
  30705. this._projectionModeMatrix.m[15] = 1.0;
  30706. var projectionMatrix = scene.getProjectionMatrix();
  30707. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30708. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30709. break;
  30710. default:
  30711. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30712. break;
  30713. }
  30714. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30715. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30716. });
  30717. return this._cachedTextureMatrix;
  30718. };
  30719. Texture.prototype.clone = function () {
  30720. var _this = this;
  30721. return BABYLON.SerializationHelper.Clone(function () {
  30722. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30723. }, this);
  30724. };
  30725. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30726. get: function () {
  30727. if (!this._onLoadObservable) {
  30728. this._onLoadObservable = new BABYLON.Observable();
  30729. }
  30730. return this._onLoadObservable;
  30731. },
  30732. enumerable: true,
  30733. configurable: true
  30734. });
  30735. Texture.prototype.serialize = function () {
  30736. var serializationObject = _super.prototype.serialize.call(this);
  30737. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30738. serializationObject.base64String = this._buffer;
  30739. serializationObject.name = serializationObject.name.replace("data:", "");
  30740. }
  30741. serializationObject.invertY = this._invertY;
  30742. serializationObject.samplingMode = this.samplingMode;
  30743. return serializationObject;
  30744. };
  30745. Texture.prototype.getClassName = function () {
  30746. return "Texture";
  30747. };
  30748. Texture.prototype.dispose = function () {
  30749. _super.prototype.dispose.call(this);
  30750. if (this._onLoadObservable) {
  30751. this._onLoadObservable.clear();
  30752. this._onLoadObservable = null;
  30753. }
  30754. this._delayedOnLoad = null;
  30755. this._delayedOnError = null;
  30756. };
  30757. // Statics
  30758. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30759. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30760. if (onLoad === void 0) { onLoad = null; }
  30761. if (onError === void 0) { onError = null; }
  30762. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30763. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30764. };
  30765. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30766. if (parsedTexture.customType) {
  30767. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30768. // Update Sampling Mode
  30769. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30770. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30771. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30772. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30773. }
  30774. }
  30775. return parsedCustomTexture;
  30776. }
  30777. if (parsedTexture.isCube) {
  30778. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30779. }
  30780. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30781. return null;
  30782. }
  30783. var texture = BABYLON.SerializationHelper.Parse(function () {
  30784. var generateMipMaps = true;
  30785. if (parsedTexture.noMipmap) {
  30786. generateMipMaps = false;
  30787. }
  30788. if (parsedTexture.mirrorPlane) {
  30789. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30790. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30791. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30792. return mirrorTexture;
  30793. }
  30794. else if (parsedTexture.isRenderTarget) {
  30795. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30796. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30797. return renderTargetTexture;
  30798. }
  30799. else {
  30800. var texture;
  30801. if (parsedTexture.base64String) {
  30802. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30803. }
  30804. else {
  30805. var url = rootUrl + parsedTexture.name;
  30806. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30807. url = parsedTexture.url;
  30808. }
  30809. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30810. }
  30811. return texture;
  30812. }
  30813. }, parsedTexture, scene);
  30814. // Update Sampling Mode
  30815. if (parsedTexture.samplingMode) {
  30816. var sampling = parsedTexture.samplingMode;
  30817. if (texture._samplingMode !== sampling) {
  30818. texture.updateSamplingMode(sampling);
  30819. }
  30820. }
  30821. // Animations
  30822. if (parsedTexture.animations) {
  30823. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30824. var parsedAnimation = parsedTexture.animations[animationIndex];
  30825. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30826. }
  30827. }
  30828. return texture;
  30829. };
  30830. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30831. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30832. if (noMipmap === void 0) { noMipmap = false; }
  30833. if (invertY === void 0) { invertY = true; }
  30834. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30835. if (onLoad === void 0) { onLoad = null; }
  30836. if (onError === void 0) { onError = null; }
  30837. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30838. if (name.substr(0, 5) !== "data:") {
  30839. name = "data:" + name;
  30840. }
  30841. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30842. };
  30843. // Constants
  30844. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30845. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30846. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30847. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30848. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30849. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30850. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30851. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30852. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30853. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30854. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30855. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30856. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30857. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30858. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30859. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30860. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30861. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30862. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30863. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30864. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30865. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30866. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30867. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30868. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30869. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30870. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30871. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30872. /**
  30873. * 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
  30874. */
  30875. Texture.UseSerializedUrlIfAny = false;
  30876. __decorate([
  30877. BABYLON.serialize()
  30878. ], Texture.prototype, "url", void 0);
  30879. __decorate([
  30880. BABYLON.serialize()
  30881. ], Texture.prototype, "uOffset", void 0);
  30882. __decorate([
  30883. BABYLON.serialize()
  30884. ], Texture.prototype, "vOffset", void 0);
  30885. __decorate([
  30886. BABYLON.serialize()
  30887. ], Texture.prototype, "uScale", void 0);
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], Texture.prototype, "vScale", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], Texture.prototype, "uAng", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], Texture.prototype, "vAng", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], Texture.prototype, "wAng", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], Texture.prototype, "uRotationCenter", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], Texture.prototype, "vRotationCenter", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "wRotationCenter", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], Texture.prototype, "isBlocking", null);
  30912. return Texture;
  30913. }(BABYLON.BaseTexture));
  30914. BABYLON.Texture = Texture;
  30915. })(BABYLON || (BABYLON = {}));
  30916. //# sourceMappingURL=babylon.texture.js.map
  30917. var BABYLON;
  30918. (function (BABYLON) {
  30919. /**
  30920. * @hidden
  30921. **/
  30922. var _InstancesBatch = /** @class */ (function () {
  30923. function _InstancesBatch() {
  30924. this.mustReturn = false;
  30925. this.visibleInstances = new Array();
  30926. this.renderSelf = new Array();
  30927. }
  30928. return _InstancesBatch;
  30929. }());
  30930. BABYLON._InstancesBatch = _InstancesBatch;
  30931. /**
  30932. * Class used to represent renderable models
  30933. */
  30934. var Mesh = /** @class */ (function (_super) {
  30935. __extends(Mesh, _super);
  30936. /**
  30937. * @constructor
  30938. * @param name The value used by scene.getMeshByName() to do a lookup.
  30939. * @param scene The scene to add this mesh to.
  30940. * @param parent The parent of this mesh, if it has one
  30941. * @param source An optional Mesh from which geometry is shared, cloned.
  30942. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30943. * When false, achieved by calling a clone(), also passing False.
  30944. * This will make creation of children, recursive.
  30945. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30946. */
  30947. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30948. if (scene === void 0) { scene = null; }
  30949. if (parent === void 0) { parent = null; }
  30950. if (source === void 0) { source = null; }
  30951. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30952. var _this = _super.call(this, name, scene) || this;
  30953. // Members
  30954. /**
  30955. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30956. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30957. */
  30958. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30959. /**
  30960. * Gets the list of instances created from this mesh
  30961. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30962. */
  30963. _this.instances = new Array();
  30964. _this._LODLevels = new Array();
  30965. /** @hidden */
  30966. _this._visibleInstances = {};
  30967. _this._renderIdForInstances = new Array();
  30968. _this._batchCache = new _InstancesBatch();
  30969. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30970. // Use by builder only to know what orientation were the mesh build in.
  30971. /** @hidden */
  30972. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30973. /**
  30974. * Use this property to change the original side orientation defined at construction time
  30975. */
  30976. _this.overrideMaterialSideOrientation = null;
  30977. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30978. // Will be used to save a source mesh reference, If any
  30979. _this._source = null;
  30980. scene = _this.getScene();
  30981. if (source) {
  30982. // Geometry
  30983. if (source._geometry) {
  30984. source._geometry.applyToMesh(_this);
  30985. }
  30986. // Deep copy
  30987. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30988. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30989. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30990. ], ["_poseMatrix"]);
  30991. // Source mesh
  30992. _this._source = source;
  30993. // Construction Params
  30994. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30995. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30996. var myAnyThis = _this;
  30997. var myAnySource = source;
  30998. myAnyThis._closePath = myAnySource._closePath;
  30999. myAnyThis._idx = myAnySource._idx;
  31000. myAnyThis.dashSize = myAnySource.dashSize;
  31001. myAnyThis.gapSize = myAnySource.gapSize;
  31002. myAnyThis.path3D = myAnySource.path3D;
  31003. myAnyThis.pathArray = myAnySource.pathArray;
  31004. myAnyThis.arc = myAnySource.arc;
  31005. myAnyThis.radius = myAnySource.radius;
  31006. // Animation ranges
  31007. if (_this._source._ranges) {
  31008. var ranges = _this._source._ranges;
  31009. for (var name in ranges) {
  31010. if (!ranges.hasOwnProperty(name)) {
  31011. continue;
  31012. }
  31013. if (!ranges[name]) {
  31014. continue;
  31015. }
  31016. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31017. }
  31018. }
  31019. // Metadata
  31020. if (source.metadata && source.metadata.clone) {
  31021. _this.metadata = source.metadata.clone();
  31022. }
  31023. else {
  31024. _this.metadata = source.metadata;
  31025. }
  31026. // Tags
  31027. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31028. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31029. }
  31030. // Parent
  31031. _this.parent = source.parent;
  31032. // Pivot
  31033. _this.setPivotMatrix(source.getPivotMatrix());
  31034. _this.id = name + "." + source.id;
  31035. // Material
  31036. _this.material = source.material;
  31037. var index;
  31038. if (!doNotCloneChildren) {
  31039. // Children
  31040. var directDescendants = source.getDescendants(true);
  31041. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31042. var child = directDescendants[index_1];
  31043. if (child.clone) {
  31044. child.clone(name + "." + child.name, _this);
  31045. }
  31046. }
  31047. }
  31048. // Physics clone
  31049. var physicsEngine = _this.getScene().getPhysicsEngine();
  31050. if (clonePhysicsImpostor && physicsEngine) {
  31051. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31052. if (impostor) {
  31053. _this.physicsImpostor = impostor.clone(_this);
  31054. }
  31055. }
  31056. // Particles
  31057. for (index = 0; index < scene.particleSystems.length; index++) {
  31058. var system = scene.particleSystems[index];
  31059. if (system.emitter === source) {
  31060. system.clone(system.name, _this);
  31061. }
  31062. }
  31063. _this.refreshBoundingInfo();
  31064. _this.computeWorldMatrix(true);
  31065. }
  31066. // Parent
  31067. if (parent !== null) {
  31068. _this.parent = parent;
  31069. }
  31070. return _this;
  31071. }
  31072. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31073. /**
  31074. * An event triggered before rendering the mesh
  31075. */
  31076. get: function () {
  31077. if (!this._onBeforeRenderObservable) {
  31078. this._onBeforeRenderObservable = new BABYLON.Observable();
  31079. }
  31080. return this._onBeforeRenderObservable;
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31086. /**
  31087. * An event triggered after rendering the mesh
  31088. */
  31089. get: function () {
  31090. if (!this._onAfterRenderObservable) {
  31091. this._onAfterRenderObservable = new BABYLON.Observable();
  31092. }
  31093. return this._onAfterRenderObservable;
  31094. },
  31095. enumerable: true,
  31096. configurable: true
  31097. });
  31098. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31099. /**
  31100. * An event triggered before drawing the mesh
  31101. */
  31102. get: function () {
  31103. if (!this._onBeforeDrawObservable) {
  31104. this._onBeforeDrawObservable = new BABYLON.Observable();
  31105. }
  31106. return this._onBeforeDrawObservable;
  31107. },
  31108. enumerable: true,
  31109. configurable: true
  31110. });
  31111. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31112. /**
  31113. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31114. */
  31115. set: function (callback) {
  31116. if (this._onBeforeDrawObserver) {
  31117. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31118. }
  31119. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31125. /**
  31126. * Gets or sets the morph target manager
  31127. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31128. */
  31129. get: function () {
  31130. return this._morphTargetManager;
  31131. },
  31132. set: function (value) {
  31133. if (this._morphTargetManager === value) {
  31134. return;
  31135. }
  31136. this._morphTargetManager = value;
  31137. this._syncGeometryWithMorphTargetManager();
  31138. },
  31139. enumerable: true,
  31140. configurable: true
  31141. });
  31142. Object.defineProperty(Mesh.prototype, "source", {
  31143. /**
  31144. * Gets the source mesh (the one used to clone this one from)
  31145. */
  31146. get: function () {
  31147. return this._source;
  31148. },
  31149. enumerable: true,
  31150. configurable: true
  31151. });
  31152. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31153. /**
  31154. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31155. */
  31156. get: function () {
  31157. return this._unIndexed;
  31158. },
  31159. set: function (value) {
  31160. if (this._unIndexed !== value) {
  31161. this._unIndexed = value;
  31162. this._markSubMeshesAsAttributesDirty();
  31163. }
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. // Methods
  31169. /**
  31170. * Gets the class name
  31171. * @returns the string "Mesh".
  31172. */
  31173. Mesh.prototype.getClassName = function () {
  31174. return "Mesh";
  31175. };
  31176. /**
  31177. * Returns a description of this mesh
  31178. * @param fullDetails define if full details about this mesh must be used
  31179. * @returns a descriptive string representing this mesh
  31180. */
  31181. Mesh.prototype.toString = function (fullDetails) {
  31182. var ret = _super.prototype.toString.call(this, fullDetails);
  31183. ret += ", n vertices: " + this.getTotalVertices();
  31184. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31185. if (this.animations) {
  31186. for (var i = 0; i < this.animations.length; i++) {
  31187. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31188. }
  31189. }
  31190. if (fullDetails) {
  31191. if (this._geometry) {
  31192. var ib = this.getIndices();
  31193. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31194. if (vb && ib) {
  31195. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31196. }
  31197. }
  31198. else {
  31199. ret += ", flat shading: UNKNOWN";
  31200. }
  31201. }
  31202. return ret;
  31203. };
  31204. /** @hidden */
  31205. Mesh.prototype._unBindEffect = function () {
  31206. _super.prototype._unBindEffect.call(this);
  31207. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31208. var instance = _a[_i];
  31209. instance._unBindEffect();
  31210. }
  31211. };
  31212. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31213. /**
  31214. * Gets a boolean indicating if this mesh has LOD
  31215. */
  31216. get: function () {
  31217. return this._LODLevels.length > 0;
  31218. },
  31219. enumerable: true,
  31220. configurable: true
  31221. });
  31222. /**
  31223. * Gets the list of MeshLODLevel associated with the current mesh
  31224. * @returns an array of MeshLODLevel
  31225. */
  31226. Mesh.prototype.getLODLevels = function () {
  31227. return this._LODLevels;
  31228. };
  31229. Mesh.prototype._sortLODLevels = function () {
  31230. this._LODLevels.sort(function (a, b) {
  31231. if (a.distance < b.distance) {
  31232. return 1;
  31233. }
  31234. if (a.distance > b.distance) {
  31235. return -1;
  31236. }
  31237. return 0;
  31238. });
  31239. };
  31240. /**
  31241. * Add a mesh as LOD level triggered at the given distance.
  31242. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31243. * @param distance The distance from the center of the object to show this level
  31244. * @param mesh The mesh to be added as LOD level (can be null)
  31245. * @return This mesh (for chaining)
  31246. */
  31247. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31248. if (mesh && mesh._masterMesh) {
  31249. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31250. return this;
  31251. }
  31252. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31253. this._LODLevels.push(level);
  31254. if (mesh) {
  31255. mesh._masterMesh = this;
  31256. }
  31257. this._sortLODLevels();
  31258. return this;
  31259. };
  31260. /**
  31261. * Returns the LOD level mesh at the passed distance or null if not found.
  31262. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31263. * @param distance The distance from the center of the object to show this level
  31264. * @returns a Mesh or `null`
  31265. */
  31266. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31267. for (var index = 0; index < this._LODLevels.length; index++) {
  31268. var level = this._LODLevels[index];
  31269. if (level.distance === distance) {
  31270. return level.mesh;
  31271. }
  31272. }
  31273. return null;
  31274. };
  31275. /**
  31276. * Remove a mesh from the LOD array
  31277. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31278. * @param mesh defines the mesh to be removed
  31279. * @return This mesh (for chaining)
  31280. */
  31281. Mesh.prototype.removeLODLevel = function (mesh) {
  31282. for (var index = 0; index < this._LODLevels.length; index++) {
  31283. if (this._LODLevels[index].mesh === mesh) {
  31284. this._LODLevels.splice(index, 1);
  31285. if (mesh) {
  31286. mesh._masterMesh = null;
  31287. }
  31288. }
  31289. }
  31290. this._sortLODLevels();
  31291. return this;
  31292. };
  31293. /**
  31294. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31295. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31296. * @param camera defines the camera to use to compute distance
  31297. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31298. * @return This mesh (for chaining)
  31299. */
  31300. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31301. if (!this._LODLevels || this._LODLevels.length === 0) {
  31302. return this;
  31303. }
  31304. var bSphere;
  31305. if (boundingSphere) {
  31306. bSphere = boundingSphere;
  31307. }
  31308. else {
  31309. var boundingInfo = this.getBoundingInfo();
  31310. bSphere = boundingInfo.boundingSphere;
  31311. }
  31312. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31313. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31314. if (this.onLODLevelSelection) {
  31315. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31316. }
  31317. return this;
  31318. }
  31319. for (var index = 0; index < this._LODLevels.length; index++) {
  31320. var level = this._LODLevels[index];
  31321. if (level.distance < distanceToCamera) {
  31322. if (level.mesh) {
  31323. level.mesh._preActivate();
  31324. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31325. }
  31326. if (this.onLODLevelSelection) {
  31327. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31328. }
  31329. return level.mesh;
  31330. }
  31331. }
  31332. if (this.onLODLevelSelection) {
  31333. this.onLODLevelSelection(distanceToCamera, this, this);
  31334. }
  31335. return this;
  31336. };
  31337. Object.defineProperty(Mesh.prototype, "geometry", {
  31338. /**
  31339. * Gets the mesh internal Geometry object
  31340. */
  31341. get: function () {
  31342. return this._geometry;
  31343. },
  31344. enumerable: true,
  31345. configurable: true
  31346. });
  31347. /**
  31348. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31349. * @returns the total number of vertices
  31350. */
  31351. Mesh.prototype.getTotalVertices = function () {
  31352. if (this._geometry === null || this._geometry === undefined) {
  31353. return 0;
  31354. }
  31355. return this._geometry.getTotalVertices();
  31356. };
  31357. /**
  31358. * Returns the content of an associated vertex buffer
  31359. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31360. * - BABYLON.VertexBuffer.PositionKind
  31361. * - BABYLON.VertexBuffer.UVKind
  31362. * - BABYLON.VertexBuffer.UV2Kind
  31363. * - BABYLON.VertexBuffer.UV3Kind
  31364. * - BABYLON.VertexBuffer.UV4Kind
  31365. * - BABYLON.VertexBuffer.UV5Kind
  31366. * - BABYLON.VertexBuffer.UV6Kind
  31367. * - BABYLON.VertexBuffer.ColorKind
  31368. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31369. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31370. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31371. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31372. * @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
  31373. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31374. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31375. */
  31376. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31377. if (!this._geometry) {
  31378. return null;
  31379. }
  31380. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31381. };
  31382. /**
  31383. * Returns the mesh VertexBuffer object from the requested `kind`
  31384. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31385. * - BABYLON.VertexBuffer.PositionKind
  31386. * - BABYLON.VertexBuffer.UVKind
  31387. * - BABYLON.VertexBuffer.UV2Kind
  31388. * - BABYLON.VertexBuffer.UV3Kind
  31389. * - BABYLON.VertexBuffer.UV4Kind
  31390. * - BABYLON.VertexBuffer.UV5Kind
  31391. * - BABYLON.VertexBuffer.UV6Kind
  31392. * - BABYLON.VertexBuffer.ColorKind
  31393. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31394. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31395. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31396. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31397. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31398. */
  31399. Mesh.prototype.getVertexBuffer = function (kind) {
  31400. if (!this._geometry) {
  31401. return null;
  31402. }
  31403. return this._geometry.getVertexBuffer(kind);
  31404. };
  31405. /**
  31406. * Tests if a specific vertex buffer is associated with this mesh
  31407. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31408. * - BABYLON.VertexBuffer.PositionKind
  31409. * - BABYLON.VertexBuffer.UVKind
  31410. * - BABYLON.VertexBuffer.UV2Kind
  31411. * - BABYLON.VertexBuffer.UV3Kind
  31412. * - BABYLON.VertexBuffer.UV4Kind
  31413. * - BABYLON.VertexBuffer.UV5Kind
  31414. * - BABYLON.VertexBuffer.UV6Kind
  31415. * - BABYLON.VertexBuffer.ColorKind
  31416. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31417. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31418. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31419. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31420. * @returns a boolean
  31421. */
  31422. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31423. if (!this._geometry) {
  31424. if (this._delayInfo) {
  31425. return this._delayInfo.indexOf(kind) !== -1;
  31426. }
  31427. return false;
  31428. }
  31429. return this._geometry.isVerticesDataPresent(kind);
  31430. };
  31431. /**
  31432. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31433. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31434. * - BABYLON.VertexBuffer.PositionKind
  31435. * - BABYLON.VertexBuffer.UVKind
  31436. * - BABYLON.VertexBuffer.UV2Kind
  31437. * - BABYLON.VertexBuffer.UV3Kind
  31438. * - BABYLON.VertexBuffer.UV4Kind
  31439. * - BABYLON.VertexBuffer.UV5Kind
  31440. * - BABYLON.VertexBuffer.UV6Kind
  31441. * - BABYLON.VertexBuffer.ColorKind
  31442. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31443. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31444. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31445. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31446. * @returns a boolean
  31447. */
  31448. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31449. if (!this._geometry) {
  31450. if (this._delayInfo) {
  31451. return this._delayInfo.indexOf(kind) !== -1;
  31452. }
  31453. return false;
  31454. }
  31455. return this._geometry.isVertexBufferUpdatable(kind);
  31456. };
  31457. /**
  31458. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31459. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31460. * - BABYLON.VertexBuffer.PositionKind
  31461. * - BABYLON.VertexBuffer.UVKind
  31462. * - BABYLON.VertexBuffer.UV2Kind
  31463. * - BABYLON.VertexBuffer.UV3Kind
  31464. * - BABYLON.VertexBuffer.UV4Kind
  31465. * - BABYLON.VertexBuffer.UV5Kind
  31466. * - BABYLON.VertexBuffer.UV6Kind
  31467. * - BABYLON.VertexBuffer.ColorKind
  31468. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31469. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31470. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31471. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31472. * @returns an array of strings
  31473. */
  31474. Mesh.prototype.getVerticesDataKinds = function () {
  31475. if (!this._geometry) {
  31476. var result = new Array();
  31477. if (this._delayInfo) {
  31478. this._delayInfo.forEach(function (kind, index, array) {
  31479. result.push(kind);
  31480. });
  31481. }
  31482. return result;
  31483. }
  31484. return this._geometry.getVerticesDataKinds();
  31485. };
  31486. /**
  31487. * Returns a positive integer : the total number of indices in this mesh geometry.
  31488. * @returns the numner of indices or zero if the mesh has no geometry.
  31489. */
  31490. Mesh.prototype.getTotalIndices = function () {
  31491. if (!this._geometry) {
  31492. return 0;
  31493. }
  31494. return this._geometry.getTotalIndices();
  31495. };
  31496. /**
  31497. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31498. * @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.
  31499. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31500. * @returns the indices array or an empty array if the mesh has no geometry
  31501. */
  31502. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31503. if (!this._geometry) {
  31504. return [];
  31505. }
  31506. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31507. };
  31508. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31509. get: function () {
  31510. return this._masterMesh !== null && this._masterMesh !== undefined;
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. /**
  31516. * Determine if the current mesh is ready to be rendered
  31517. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31518. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31519. * @returns true if all associated assets are ready (material, textures, shaders)
  31520. */
  31521. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31522. if (completeCheck === void 0) { completeCheck = false; }
  31523. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31524. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31525. return false;
  31526. }
  31527. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31528. return false;
  31529. }
  31530. if (!this.subMeshes || this.subMeshes.length === 0) {
  31531. return true;
  31532. }
  31533. if (!completeCheck) {
  31534. return true;
  31535. }
  31536. var engine = this.getEngine();
  31537. var scene = this.getScene();
  31538. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31539. this.computeWorldMatrix();
  31540. var mat = this.material || scene.defaultMaterial;
  31541. if (mat) {
  31542. if (mat.storeEffectOnSubMeshes) {
  31543. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31544. var subMesh = _a[_i];
  31545. var effectiveMaterial = subMesh.getMaterial();
  31546. if (effectiveMaterial) {
  31547. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31548. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31549. return false;
  31550. }
  31551. }
  31552. else {
  31553. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31554. return false;
  31555. }
  31556. }
  31557. }
  31558. }
  31559. }
  31560. else {
  31561. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31562. return false;
  31563. }
  31564. }
  31565. }
  31566. // Shadows
  31567. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31568. var light = _c[_b];
  31569. var generator = light.getShadowGenerator();
  31570. if (generator) {
  31571. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31572. var subMesh = _e[_d];
  31573. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31574. return false;
  31575. }
  31576. }
  31577. }
  31578. }
  31579. // LOD
  31580. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31581. var lod = _g[_f];
  31582. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31583. return false;
  31584. }
  31585. }
  31586. return true;
  31587. };
  31588. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31589. /**
  31590. * 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.
  31591. */
  31592. get: function () {
  31593. return this._areNormalsFrozen;
  31594. },
  31595. enumerable: true,
  31596. configurable: true
  31597. });
  31598. /**
  31599. * 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.
  31600. * @returns the current mesh
  31601. */
  31602. Mesh.prototype.freezeNormals = function () {
  31603. this._areNormalsFrozen = true;
  31604. return this;
  31605. };
  31606. /**
  31607. * 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
  31608. * @returns the current mesh
  31609. */
  31610. Mesh.prototype.unfreezeNormals = function () {
  31611. this._areNormalsFrozen = false;
  31612. return this;
  31613. };
  31614. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31615. /**
  31616. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31617. */
  31618. set: function (count) {
  31619. this._overridenInstanceCount = count;
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. // Methods
  31625. /** @hidden */
  31626. Mesh.prototype._preActivate = function () {
  31627. var sceneRenderId = this.getScene().getRenderId();
  31628. if (this._preActivateId === sceneRenderId) {
  31629. return this;
  31630. }
  31631. this._preActivateId = sceneRenderId;
  31632. this._visibleInstances = null;
  31633. return this;
  31634. };
  31635. /** @hidden */
  31636. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31637. if (this._visibleInstances) {
  31638. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31639. }
  31640. return this;
  31641. };
  31642. /** @hidden */
  31643. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31644. if (!this._visibleInstances) {
  31645. this._visibleInstances = {};
  31646. this._visibleInstances.defaultRenderId = renderId;
  31647. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31648. }
  31649. if (!this._visibleInstances[renderId]) {
  31650. this._visibleInstances[renderId] = new Array();
  31651. }
  31652. this._visibleInstances[renderId].push(instance);
  31653. return this;
  31654. };
  31655. /**
  31656. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31657. * This means the mesh underlying bounding box and sphere are recomputed.
  31658. * @returns the current mesh
  31659. */
  31660. Mesh.prototype.refreshBoundingInfo = function () {
  31661. return this._refreshBoundingInfo(false);
  31662. };
  31663. /** @hidden */
  31664. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31665. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31666. return this;
  31667. }
  31668. var data = this._getPositionData(applySkeleton);
  31669. if (data) {
  31670. var bias = this.geometry ? this.geometry.boundingBias : null;
  31671. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31672. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31673. }
  31674. if (this.subMeshes) {
  31675. for (var index = 0; index < this.subMeshes.length; index++) {
  31676. this.subMeshes[index].refreshBoundingInfo();
  31677. }
  31678. }
  31679. this._updateBoundingInfo();
  31680. return this;
  31681. };
  31682. Mesh.prototype._getPositionData = function (applySkeleton) {
  31683. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31684. if (data && applySkeleton && this.skeleton) {
  31685. data = BABYLON.Tools.Slice(data);
  31686. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31687. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31688. if (matricesWeightsData && matricesIndicesData) {
  31689. var needExtras = this.numBoneInfluencers > 4;
  31690. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31691. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31692. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31693. var tempVector = BABYLON.Tmp.Vector3[0];
  31694. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31695. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31696. var matWeightIdx = 0;
  31697. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31698. finalMatrix.reset();
  31699. var inf;
  31700. var weight;
  31701. for (inf = 0; inf < 4; inf++) {
  31702. weight = matricesWeightsData[matWeightIdx + inf];
  31703. if (weight > 0) {
  31704. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31705. finalMatrix.addToSelf(tempMatrix);
  31706. }
  31707. }
  31708. if (needExtras) {
  31709. for (inf = 0; inf < 4; inf++) {
  31710. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31711. if (weight > 0) {
  31712. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31713. finalMatrix.addToSelf(tempMatrix);
  31714. }
  31715. }
  31716. }
  31717. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31718. tempVector.toArray(data, index);
  31719. }
  31720. }
  31721. }
  31722. return data;
  31723. };
  31724. /** @hidden */
  31725. Mesh.prototype._createGlobalSubMesh = function (force) {
  31726. var totalVertices = this.getTotalVertices();
  31727. if (!totalVertices || !this.getIndices()) {
  31728. return null;
  31729. }
  31730. // Check if we need to recreate the submeshes
  31731. if (this.subMeshes && this.subMeshes.length > 0) {
  31732. var ib = this.getIndices();
  31733. if (!ib) {
  31734. return null;
  31735. }
  31736. var totalIndices = ib.length;
  31737. var needToRecreate = false;
  31738. if (force) {
  31739. needToRecreate = true;
  31740. }
  31741. else {
  31742. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31743. var submesh = _a[_i];
  31744. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31745. needToRecreate = true;
  31746. break;
  31747. }
  31748. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31749. needToRecreate = true;
  31750. break;
  31751. }
  31752. }
  31753. }
  31754. if (!needToRecreate) {
  31755. return this.subMeshes[0];
  31756. }
  31757. }
  31758. this.releaseSubMeshes();
  31759. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31760. };
  31761. /**
  31762. * This function will subdivide the mesh into multiple submeshes
  31763. * @param count defines the expected number of submeshes
  31764. */
  31765. Mesh.prototype.subdivide = function (count) {
  31766. if (count < 1) {
  31767. return;
  31768. }
  31769. var totalIndices = this.getTotalIndices();
  31770. var subdivisionSize = (totalIndices / count) | 0;
  31771. var offset = 0;
  31772. // Ensure that subdivisionSize is a multiple of 3
  31773. while (subdivisionSize % 3 !== 0) {
  31774. subdivisionSize++;
  31775. }
  31776. this.releaseSubMeshes();
  31777. for (var index = 0; index < count; index++) {
  31778. if (offset >= totalIndices) {
  31779. break;
  31780. }
  31781. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31782. offset += subdivisionSize;
  31783. }
  31784. this.synchronizeInstances();
  31785. };
  31786. /**
  31787. * Copy a FloatArray into a specific associated vertex buffer
  31788. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31789. * - BABYLON.VertexBuffer.PositionKind
  31790. * - BABYLON.VertexBuffer.UVKind
  31791. * - BABYLON.VertexBuffer.UV2Kind
  31792. * - BABYLON.VertexBuffer.UV3Kind
  31793. * - BABYLON.VertexBuffer.UV4Kind
  31794. * - BABYLON.VertexBuffer.UV5Kind
  31795. * - BABYLON.VertexBuffer.UV6Kind
  31796. * - BABYLON.VertexBuffer.ColorKind
  31797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31801. * @param data defines the data source
  31802. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31803. * @param stride defines the data stride size (can be null)
  31804. * @returns the current mesh
  31805. */
  31806. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31807. if (updatable === void 0) { updatable = false; }
  31808. if (!this._geometry) {
  31809. var vertexData = new BABYLON.VertexData();
  31810. vertexData.set(data, kind);
  31811. var scene = this.getScene();
  31812. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31813. }
  31814. else {
  31815. this._geometry.setVerticesData(kind, data, updatable, stride);
  31816. }
  31817. return this;
  31818. };
  31819. /**
  31820. * Flags an associated vertex buffer as updatable
  31821. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31822. * - BABYLON.VertexBuffer.PositionKind
  31823. * - BABYLON.VertexBuffer.UVKind
  31824. * - BABYLON.VertexBuffer.UV2Kind
  31825. * - BABYLON.VertexBuffer.UV3Kind
  31826. * - BABYLON.VertexBuffer.UV4Kind
  31827. * - BABYLON.VertexBuffer.UV5Kind
  31828. * - BABYLON.VertexBuffer.UV6Kind
  31829. * - BABYLON.VertexBuffer.ColorKind
  31830. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31831. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31832. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31833. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31834. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31835. */
  31836. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31837. if (updatable === void 0) { updatable = true; }
  31838. var vb = this.getVertexBuffer(kind);
  31839. if (!vb || vb.isUpdatable() === updatable) {
  31840. return;
  31841. }
  31842. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31843. };
  31844. /**
  31845. * Sets the mesh global Vertex Buffer
  31846. * @param buffer defines the buffer to use
  31847. * @returns the current mesh
  31848. */
  31849. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31850. if (!this._geometry) {
  31851. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31852. }
  31853. this._geometry.setVerticesBuffer(buffer);
  31854. return this;
  31855. };
  31856. /**
  31857. * Update a specific associated vertex buffer
  31858. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31859. * - BABYLON.VertexBuffer.PositionKind
  31860. * - BABYLON.VertexBuffer.UVKind
  31861. * - BABYLON.VertexBuffer.UV2Kind
  31862. * - BABYLON.VertexBuffer.UV3Kind
  31863. * - BABYLON.VertexBuffer.UV4Kind
  31864. * - BABYLON.VertexBuffer.UV5Kind
  31865. * - BABYLON.VertexBuffer.UV6Kind
  31866. * - BABYLON.VertexBuffer.ColorKind
  31867. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31868. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31869. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31870. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31871. * @param data defines the data source
  31872. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31873. * @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)
  31874. * @returns the current mesh
  31875. */
  31876. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31877. if (!this._geometry) {
  31878. return this;
  31879. }
  31880. if (!makeItUnique) {
  31881. this._geometry.updateVerticesData(kind, data, updateExtends);
  31882. }
  31883. else {
  31884. this.makeGeometryUnique();
  31885. this.updateVerticesData(kind, data, updateExtends, false);
  31886. }
  31887. return this;
  31888. };
  31889. /**
  31890. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31891. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31892. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31893. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31894. * @returns the current mesh
  31895. */
  31896. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31897. if (computeNormals === void 0) { computeNormals = true; }
  31898. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31899. if (!positions) {
  31900. return this;
  31901. }
  31902. positionFunction(positions);
  31903. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31904. if (computeNormals) {
  31905. var indices = this.getIndices();
  31906. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31907. if (!normals) {
  31908. return this;
  31909. }
  31910. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31911. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31912. }
  31913. return this;
  31914. };
  31915. /**
  31916. * Creates a un-shared specific occurence of the geometry for the mesh.
  31917. * @returns the current mesh
  31918. */
  31919. Mesh.prototype.makeGeometryUnique = function () {
  31920. if (!this._geometry) {
  31921. return this;
  31922. }
  31923. var oldGeometry = this._geometry;
  31924. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31925. oldGeometry.releaseForMesh(this, true);
  31926. geometry.applyToMesh(this);
  31927. return this;
  31928. };
  31929. /**
  31930. * Set the index buffer of this mesh
  31931. * @param indices defines the source data
  31932. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31933. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31934. * @returns the current mesh
  31935. */
  31936. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31937. if (totalVertices === void 0) { totalVertices = null; }
  31938. if (updatable === void 0) { updatable = false; }
  31939. if (!this._geometry) {
  31940. var vertexData = new BABYLON.VertexData();
  31941. vertexData.indices = indices;
  31942. var scene = this.getScene();
  31943. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31944. }
  31945. else {
  31946. this._geometry.setIndices(indices, totalVertices, updatable);
  31947. }
  31948. return this;
  31949. };
  31950. /**
  31951. * Update the current index buffer
  31952. * @param indices defines the source data
  31953. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31954. * @returns the current mesh
  31955. */
  31956. Mesh.prototype.updateIndices = function (indices, offset) {
  31957. if (!this._geometry) {
  31958. return this;
  31959. }
  31960. this._geometry.updateIndices(indices, offset);
  31961. return this;
  31962. };
  31963. /**
  31964. * Invert the geometry to move from a right handed system to a left handed one.
  31965. * @returns the current mesh
  31966. */
  31967. Mesh.prototype.toLeftHanded = function () {
  31968. if (!this._geometry) {
  31969. return this;
  31970. }
  31971. this._geometry.toLeftHanded();
  31972. return this;
  31973. };
  31974. /** @hidden */
  31975. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31976. if (!this._geometry) {
  31977. return this;
  31978. }
  31979. var engine = this.getScene().getEngine();
  31980. // Wireframe
  31981. var indexToBind;
  31982. if (this._unIndexed) {
  31983. indexToBind = null;
  31984. }
  31985. else {
  31986. switch (fillMode) {
  31987. case BABYLON.Material.PointFillMode:
  31988. indexToBind = null;
  31989. break;
  31990. case BABYLON.Material.WireFrameFillMode:
  31991. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31992. break;
  31993. default:
  31994. case BABYLON.Material.TriangleFillMode:
  31995. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31996. break;
  31997. }
  31998. }
  31999. // VBOs
  32000. this._geometry._bind(effect, indexToBind);
  32001. return this;
  32002. };
  32003. /** @hidden */
  32004. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32005. if (alternate === void 0) { alternate = false; }
  32006. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32007. return this;
  32008. }
  32009. if (this._onBeforeDrawObservable) {
  32010. this._onBeforeDrawObservable.notifyObservers(this);
  32011. }
  32012. var scene = this.getScene();
  32013. var engine = scene.getEngine();
  32014. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32015. // or triangles as points
  32016. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32017. }
  32018. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32019. // Triangles as wireframe
  32020. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32021. }
  32022. else {
  32023. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32024. }
  32025. if (scene._isAlternateRenderingEnabled && !alternate) {
  32026. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32027. if (!effect || !scene.activeCamera) {
  32028. return this;
  32029. }
  32030. scene._switchToAlternateCameraConfiguration(true);
  32031. this._effectiveMaterial.bindView(effect);
  32032. this._effectiveMaterial.bindViewProjection(effect);
  32033. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32034. this._draw(subMesh, fillMode, instancesCount, true);
  32035. engine.setViewport(scene.activeCamera.viewport);
  32036. scene._switchToAlternateCameraConfiguration(false);
  32037. this._effectiveMaterial.bindView(effect);
  32038. this._effectiveMaterial.bindViewProjection(effect);
  32039. }
  32040. return this;
  32041. };
  32042. /**
  32043. * Registers for this mesh a javascript function called just before the rendering process
  32044. * @param func defines the function to call before rendering this mesh
  32045. * @returns the current mesh
  32046. */
  32047. Mesh.prototype.registerBeforeRender = function (func) {
  32048. this.onBeforeRenderObservable.add(func);
  32049. return this;
  32050. };
  32051. /**
  32052. * Disposes a previously registered javascript function called before the rendering
  32053. * @param func defines the function to remove
  32054. * @returns the current mesh
  32055. */
  32056. Mesh.prototype.unregisterBeforeRender = function (func) {
  32057. this.onBeforeRenderObservable.removeCallback(func);
  32058. return this;
  32059. };
  32060. /**
  32061. * Registers for this mesh a javascript function called just after the rendering is complete
  32062. * @param func defines the function to call after rendering this mesh
  32063. * @returns the current mesh
  32064. */
  32065. Mesh.prototype.registerAfterRender = function (func) {
  32066. this.onAfterRenderObservable.add(func);
  32067. return this;
  32068. };
  32069. /**
  32070. * Disposes a previously registered javascript function called after the rendering.
  32071. * @param func defines the function to remove
  32072. * @returns the current mesh
  32073. */
  32074. Mesh.prototype.unregisterAfterRender = function (func) {
  32075. this.onAfterRenderObservable.removeCallback(func);
  32076. return this;
  32077. };
  32078. /** @hidden */
  32079. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32080. var scene = this.getScene();
  32081. this._batchCache.mustReturn = false;
  32082. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32083. this._batchCache.visibleInstances[subMeshId] = null;
  32084. if (this._visibleInstances) {
  32085. var currentRenderId = scene.getRenderId();
  32086. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32087. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32088. var selfRenderId = this._renderId;
  32089. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32090. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32091. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32092. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32093. }
  32094. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32095. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32096. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32097. this._batchCache.mustReturn = true;
  32098. return this._batchCache;
  32099. }
  32100. if (currentRenderId !== selfRenderId) {
  32101. this._batchCache.renderSelf[subMeshId] = false;
  32102. }
  32103. }
  32104. this._renderIdForInstances[subMeshId] = currentRenderId;
  32105. }
  32106. return this._batchCache;
  32107. };
  32108. /** @hidden */
  32109. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32110. var visibleInstances = batch.visibleInstances[subMesh._id];
  32111. if (!visibleInstances) {
  32112. return this;
  32113. }
  32114. var matricesCount = visibleInstances.length + 1;
  32115. var bufferSize = matricesCount * 16 * 4;
  32116. var currentInstancesBufferSize = this._instancesBufferSize;
  32117. var instancesBuffer = this._instancesBuffer;
  32118. while (this._instancesBufferSize < bufferSize) {
  32119. this._instancesBufferSize *= 2;
  32120. }
  32121. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32122. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32123. }
  32124. var offset = 0;
  32125. var instancesCount = 0;
  32126. var world = this.getWorldMatrix();
  32127. if (batch.renderSelf[subMesh._id]) {
  32128. world.copyToArray(this._instancesData, offset);
  32129. offset += 16;
  32130. instancesCount++;
  32131. }
  32132. if (visibleInstances) {
  32133. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32134. var instance = visibleInstances[instanceIndex];
  32135. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32136. offset += 16;
  32137. instancesCount++;
  32138. }
  32139. }
  32140. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32141. if (instancesBuffer) {
  32142. instancesBuffer.dispose();
  32143. }
  32144. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32145. this._instancesBuffer = instancesBuffer;
  32146. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32147. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32148. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32149. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32150. }
  32151. else {
  32152. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32153. }
  32154. this._bind(subMesh, effect, fillMode);
  32155. this._draw(subMesh, fillMode, instancesCount);
  32156. engine.unbindInstanceAttributes();
  32157. return this;
  32158. };
  32159. /** @hidden */
  32160. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32161. var scene = this.getScene();
  32162. var engine = scene.getEngine();
  32163. if (hardwareInstancedRendering) {
  32164. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32165. }
  32166. else {
  32167. if (batch.renderSelf[subMesh._id]) {
  32168. // Draw
  32169. if (onBeforeDraw) {
  32170. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32171. }
  32172. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32173. }
  32174. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32175. if (visibleInstancesForSubMesh) {
  32176. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32177. var instance = visibleInstancesForSubMesh[instanceIndex];
  32178. // World
  32179. var world = instance.getWorldMatrix();
  32180. if (onBeforeDraw) {
  32181. onBeforeDraw(true, world, effectiveMaterial);
  32182. }
  32183. // Draw
  32184. this._draw(subMesh, fillMode);
  32185. }
  32186. }
  32187. }
  32188. return this;
  32189. };
  32190. /**
  32191. * 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
  32192. * @param subMesh defines the subMesh to render
  32193. * @param enableAlphaMode defines if alpha mode can be changed
  32194. * @returns the current mesh
  32195. */
  32196. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32197. this._checkOcclusionQuery();
  32198. if (this._isOccluded) {
  32199. return this;
  32200. }
  32201. var scene = this.getScene();
  32202. // Managing instances
  32203. var batch = this._getInstancesRenderList(subMesh._id);
  32204. if (batch.mustReturn) {
  32205. return this;
  32206. }
  32207. // Checking geometry state
  32208. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32209. return this;
  32210. }
  32211. if (this._onBeforeRenderObservable) {
  32212. this._onBeforeRenderObservable.notifyObservers(this);
  32213. }
  32214. var engine = scene.getEngine();
  32215. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32216. // Material
  32217. var material = subMesh.getMaterial();
  32218. if (!material) {
  32219. return this;
  32220. }
  32221. this._effectiveMaterial = material;
  32222. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32223. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32224. return this;
  32225. }
  32226. }
  32227. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32228. return this;
  32229. }
  32230. // Alpha mode
  32231. if (enableAlphaMode) {
  32232. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32233. }
  32234. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32235. var step = _a[_i];
  32236. step.action(this, subMesh, batch);
  32237. }
  32238. var effect;
  32239. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32240. effect = subMesh.effect;
  32241. }
  32242. else {
  32243. effect = this._effectiveMaterial.getEffect();
  32244. }
  32245. if (!effect) {
  32246. return this;
  32247. }
  32248. var sideOrientation = this.overrideMaterialSideOrientation;
  32249. if (sideOrientation == null) {
  32250. sideOrientation = this._effectiveMaterial.sideOrientation;
  32251. if (this._getWorldMatrixDeterminant() < 0) {
  32252. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32253. }
  32254. }
  32255. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32256. if (this._effectiveMaterial.forceDepthWrite) {
  32257. engine.setDepthWrite(true);
  32258. }
  32259. // Bind
  32260. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32261. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32262. this._bind(subMesh, effect, fillMode);
  32263. }
  32264. var world = this.getWorldMatrix();
  32265. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32266. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32267. }
  32268. else {
  32269. this._effectiveMaterial.bind(world, this);
  32270. }
  32271. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32272. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32273. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32274. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32275. }
  32276. // Draw
  32277. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32278. // Unbind
  32279. this._effectiveMaterial.unbind();
  32280. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32281. var step = _c[_b];
  32282. step.action(this, subMesh, batch);
  32283. }
  32284. if (this._onAfterRenderObservable) {
  32285. this._onAfterRenderObservable.notifyObservers(this);
  32286. }
  32287. return this;
  32288. };
  32289. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32290. if (isInstance && effectiveMaterial) {
  32291. effectiveMaterial.bindOnlyWorldMatrix(world);
  32292. }
  32293. };
  32294. /**
  32295. * Normalize matrix weights so that all vertices have a total weight set to 1
  32296. */
  32297. Mesh.prototype.cleanMatrixWeights = function () {
  32298. var epsilon = 1e-3;
  32299. var noInfluenceBoneIndex = 0.0;
  32300. if (this.skeleton) {
  32301. noInfluenceBoneIndex = this.skeleton.bones.length;
  32302. }
  32303. else {
  32304. return;
  32305. }
  32306. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32307. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32308. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32309. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32310. var influencers = this.numBoneInfluencers;
  32311. var size = matricesWeights.length;
  32312. for (var i = 0; i < size; i += 4) {
  32313. var weight = 0.0;
  32314. var firstZeroWeight = -1;
  32315. for (var j = 0; j < 4; j++) {
  32316. var w = matricesWeights[i + j];
  32317. weight += w;
  32318. if (w < epsilon && firstZeroWeight < 0) {
  32319. firstZeroWeight = j;
  32320. }
  32321. }
  32322. if (matricesWeightsExtra) {
  32323. for (var j = 0; j < 4; j++) {
  32324. var w = matricesWeightsExtra[i + j];
  32325. weight += w;
  32326. if (w < epsilon && firstZeroWeight < 0) {
  32327. firstZeroWeight = j + 4;
  32328. }
  32329. }
  32330. }
  32331. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32332. firstZeroWeight = influencers - 1;
  32333. }
  32334. if (weight > epsilon) {
  32335. var mweight = 1.0 / weight;
  32336. for (var j = 0; j < 4; j++) {
  32337. matricesWeights[i + j] *= mweight;
  32338. }
  32339. if (matricesWeightsExtra) {
  32340. for (var j = 0; j < 4; j++) {
  32341. matricesWeightsExtra[i + j] *= mweight;
  32342. }
  32343. }
  32344. }
  32345. else {
  32346. if (firstZeroWeight >= 4) {
  32347. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32348. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32349. }
  32350. else {
  32351. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32352. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32353. }
  32354. }
  32355. }
  32356. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32357. if (matricesIndicesExtra) {
  32358. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32359. }
  32360. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32361. if (matricesWeightsExtra) {
  32362. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32363. }
  32364. };
  32365. /** @hidden */
  32366. Mesh.prototype._checkDelayState = function () {
  32367. var scene = this.getScene();
  32368. if (this._geometry) {
  32369. this._geometry.load(scene);
  32370. }
  32371. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32373. this._queueLoad(scene);
  32374. }
  32375. return this;
  32376. };
  32377. Mesh.prototype._queueLoad = function (scene) {
  32378. var _this = this;
  32379. scene._addPendingData(this);
  32380. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32381. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32382. if (data instanceof ArrayBuffer) {
  32383. _this._delayLoadingFunction(data, _this);
  32384. }
  32385. else {
  32386. _this._delayLoadingFunction(JSON.parse(data), _this);
  32387. }
  32388. _this.instances.forEach(function (instance) {
  32389. instance._syncSubMeshes();
  32390. });
  32391. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32392. scene._removePendingData(_this);
  32393. }, function () { }, scene.database, getBinaryData);
  32394. return this;
  32395. };
  32396. /**
  32397. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32398. * A mesh is in the frustum if its bounding box intersects the frustum
  32399. * @param frustumPlanes defines the frustum to test
  32400. * @returns true if the mesh is in the frustum planes
  32401. */
  32402. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32403. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32404. return false;
  32405. }
  32406. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32407. return false;
  32408. }
  32409. this._checkDelayState();
  32410. return true;
  32411. };
  32412. /**
  32413. * Sets the mesh material by the material or multiMaterial `id` property
  32414. * @param id is a string identifying the material or the multiMaterial
  32415. * @returns the current mesh
  32416. */
  32417. Mesh.prototype.setMaterialByID = function (id) {
  32418. var materials = this.getScene().materials;
  32419. var index;
  32420. for (index = materials.length - 1; index > -1; index--) {
  32421. if (materials[index].id === id) {
  32422. this.material = materials[index];
  32423. return this;
  32424. }
  32425. }
  32426. // Multi
  32427. var multiMaterials = this.getScene().multiMaterials;
  32428. for (index = multiMaterials.length - 1; index > -1; index--) {
  32429. if (multiMaterials[index].id === id) {
  32430. this.material = multiMaterials[index];
  32431. return this;
  32432. }
  32433. }
  32434. return this;
  32435. };
  32436. /**
  32437. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32438. * @returns an array of IAnimatable
  32439. */
  32440. Mesh.prototype.getAnimatables = function () {
  32441. var results = new Array();
  32442. if (this.material) {
  32443. results.push(this.material);
  32444. }
  32445. if (this.skeleton) {
  32446. results.push(this.skeleton);
  32447. }
  32448. return results;
  32449. };
  32450. /**
  32451. * Modifies the mesh geometry according to the passed transformation matrix.
  32452. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32453. * The mesh normals are modified using the same transformation.
  32454. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32455. * @param transform defines the transform matrix to use
  32456. * @see http://doc.babylonjs.com/resources/baking_transformations
  32457. * @returns the current mesh
  32458. */
  32459. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32460. // Position
  32461. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32462. return this;
  32463. }
  32464. var submeshes = this.subMeshes.splice(0);
  32465. this._resetPointsArrayCache();
  32466. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32467. var temp = new Array();
  32468. var index;
  32469. for (index = 0; index < data.length; index += 3) {
  32470. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32471. }
  32472. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32473. // Normals
  32474. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32475. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32476. temp = [];
  32477. for (index = 0; index < data.length; index += 3) {
  32478. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32479. }
  32480. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32481. }
  32482. // flip faces?
  32483. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32484. this.flipFaces();
  32485. }
  32486. // Restore submeshes
  32487. this.releaseSubMeshes();
  32488. this.subMeshes = submeshes;
  32489. return this;
  32490. };
  32491. /**
  32492. * Modifies the mesh geometry according to its own current World Matrix.
  32493. * The mesh World Matrix is then reset.
  32494. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32495. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32496. * @see http://doc.babylonjs.com/resources/baking_transformations
  32497. * @returns the current mesh
  32498. */
  32499. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32500. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32501. this.scaling.copyFromFloats(1, 1, 1);
  32502. this.position.copyFromFloats(0, 0, 0);
  32503. this.rotation.copyFromFloats(0, 0, 0);
  32504. //only if quaternion is already set
  32505. if (this.rotationQuaternion) {
  32506. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32507. }
  32508. this._worldMatrix = BABYLON.Matrix.Identity();
  32509. return this;
  32510. };
  32511. Object.defineProperty(Mesh.prototype, "_positions", {
  32512. // Cache
  32513. /** @hidden */
  32514. get: function () {
  32515. if (this._geometry) {
  32516. return this._geometry._positions;
  32517. }
  32518. return null;
  32519. },
  32520. enumerable: true,
  32521. configurable: true
  32522. });
  32523. /** @hidden */
  32524. Mesh.prototype._resetPointsArrayCache = function () {
  32525. if (this._geometry) {
  32526. this._geometry._resetPointsArrayCache();
  32527. }
  32528. return this;
  32529. };
  32530. /** @hidden */
  32531. Mesh.prototype._generatePointsArray = function () {
  32532. if (this._geometry) {
  32533. return this._geometry._generatePointsArray();
  32534. }
  32535. return false;
  32536. };
  32537. /**
  32538. * Returns a new Mesh object generated from the current mesh properties.
  32539. * This method must not get confused with createInstance()
  32540. * @param name is a string, the name given to the new mesh
  32541. * @param newParent can be any Node object (default `null`)
  32542. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32543. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32544. * @returns a new mesh
  32545. */
  32546. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32547. if (name === void 0) { name = ""; }
  32548. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32549. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32550. };
  32551. /**
  32552. * Releases resources associated with this mesh.
  32553. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32554. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32555. */
  32556. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32557. var _this = this;
  32558. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32559. this.morphTargetManager = null;
  32560. if (this._geometry) {
  32561. this._geometry.releaseForMesh(this, true);
  32562. }
  32563. if (this._onBeforeDrawObservable) {
  32564. this._onBeforeDrawObservable.clear();
  32565. }
  32566. if (this._onBeforeRenderObservable) {
  32567. this._onBeforeRenderObservable.clear();
  32568. }
  32569. if (this._onAfterRenderObservable) {
  32570. this._onAfterRenderObservable.clear();
  32571. }
  32572. // Sources
  32573. var meshes = this.getScene().meshes;
  32574. meshes.forEach(function (abstractMesh) {
  32575. var mesh = abstractMesh;
  32576. if (mesh._source && mesh._source === _this) {
  32577. mesh._source = null;
  32578. }
  32579. });
  32580. this._source = null;
  32581. // Instances
  32582. if (this._instancesBuffer) {
  32583. this._instancesBuffer.dispose();
  32584. this._instancesBuffer = null;
  32585. }
  32586. while (this.instances.length) {
  32587. this.instances[0].dispose();
  32588. }
  32589. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32590. };
  32591. /**
  32592. * Modifies the mesh geometry according to a displacement map.
  32593. * 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.
  32594. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32595. * @param url is a string, the URL from the image file is to be downloaded.
  32596. * @param minHeight is the lower limit of the displacement.
  32597. * @param maxHeight is the upper limit of the displacement.
  32598. * @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.
  32599. * @param uvOffset is an optional vector2 used to offset UV.
  32600. * @param uvScale is an optional vector2 used to scale UV.
  32601. * @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.
  32602. * @returns the Mesh.
  32603. */
  32604. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32605. var _this = this;
  32606. if (forceUpdate === void 0) { forceUpdate = false; }
  32607. var scene = this.getScene();
  32608. var onload = function (img) {
  32609. // Getting height map data
  32610. var canvas = document.createElement("canvas");
  32611. var context = canvas.getContext("2d");
  32612. var heightMapWidth = img.width;
  32613. var heightMapHeight = img.height;
  32614. canvas.width = heightMapWidth;
  32615. canvas.height = heightMapHeight;
  32616. context.drawImage(img, 0, 0);
  32617. // Create VertexData from map data
  32618. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32619. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32620. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32621. //execute success callback, if set
  32622. if (onSuccess) {
  32623. onSuccess(_this);
  32624. }
  32625. };
  32626. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32627. return this;
  32628. };
  32629. /**
  32630. * Modifies the mesh geometry according to a displacementMap buffer.
  32631. * 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.
  32632. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32633. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32634. * @param heightMapWidth is the width of the buffer image.
  32635. * @param heightMapHeight is the height of the buffer image.
  32636. * @param minHeight is the lower limit of the displacement.
  32637. * @param maxHeight is the upper limit of the displacement.
  32638. * @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.
  32639. * @param uvOffset is an optional vector2 used to offset UV.
  32640. * @param uvScale is an optional vector2 used to scale UV.
  32641. * @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.
  32642. * @returns the Mesh.
  32643. */
  32644. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32645. if (forceUpdate === void 0) { forceUpdate = false; }
  32646. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32647. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32648. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32649. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32650. return this;
  32651. }
  32652. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32653. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32654. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32655. var position = BABYLON.Vector3.Zero();
  32656. var normal = BABYLON.Vector3.Zero();
  32657. var uv = BABYLON.Vector2.Zero();
  32658. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32659. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32660. for (var index = 0; index < positions.length; index += 3) {
  32661. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32662. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32663. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32664. // Compute height
  32665. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32666. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32667. var pos = (u + v * heightMapWidth) * 4;
  32668. var r = buffer[pos] / 255.0;
  32669. var g = buffer[pos + 1] / 255.0;
  32670. var b = buffer[pos + 2] / 255.0;
  32671. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32672. normal.normalize();
  32673. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32674. position = position.add(normal);
  32675. position.toArray(positions, index);
  32676. }
  32677. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32678. if (forceUpdate) {
  32679. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32680. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32681. }
  32682. else {
  32683. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32684. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32685. }
  32686. return this;
  32687. };
  32688. /**
  32689. * Modify the mesh to get a flat shading rendering.
  32690. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32691. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32692. * @returns current mesh
  32693. */
  32694. Mesh.prototype.convertToFlatShadedMesh = function () {
  32695. var kinds = this.getVerticesDataKinds();
  32696. var vbs = {};
  32697. var data = {};
  32698. var newdata = {};
  32699. var updatableNormals = false;
  32700. var kindIndex;
  32701. var kind;
  32702. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32703. kind = kinds[kindIndex];
  32704. var vertexBuffer = this.getVertexBuffer(kind);
  32705. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32706. updatableNormals = vertexBuffer.isUpdatable();
  32707. kinds.splice(kindIndex, 1);
  32708. kindIndex--;
  32709. continue;
  32710. }
  32711. vbs[kind] = vertexBuffer;
  32712. data[kind] = vbs[kind].getData();
  32713. newdata[kind] = [];
  32714. }
  32715. // Save previous submeshes
  32716. var previousSubmeshes = this.subMeshes.slice(0);
  32717. var indices = this.getIndices();
  32718. var totalIndices = this.getTotalIndices();
  32719. // Generating unique vertices per face
  32720. var index;
  32721. for (index = 0; index < totalIndices; index++) {
  32722. var vertexIndex = indices[index];
  32723. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32724. kind = kinds[kindIndex];
  32725. var stride = vbs[kind].getStrideSize();
  32726. for (var offset = 0; offset < stride; offset++) {
  32727. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32728. }
  32729. }
  32730. }
  32731. // Updating faces & normal
  32732. var normals = [];
  32733. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32734. for (index = 0; index < totalIndices; index += 3) {
  32735. indices[index] = index;
  32736. indices[index + 1] = index + 1;
  32737. indices[index + 2] = index + 2;
  32738. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32739. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32740. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32741. var p1p2 = p1.subtract(p2);
  32742. var p3p2 = p3.subtract(p2);
  32743. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32744. // Store same normals for every vertex
  32745. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32746. normals.push(normal.x);
  32747. normals.push(normal.y);
  32748. normals.push(normal.z);
  32749. }
  32750. }
  32751. this.setIndices(indices);
  32752. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32753. // Updating vertex buffers
  32754. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32755. kind = kinds[kindIndex];
  32756. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32757. }
  32758. // Updating submeshes
  32759. this.releaseSubMeshes();
  32760. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32761. var previousOne = previousSubmeshes[submeshIndex];
  32762. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32763. }
  32764. this.synchronizeInstances();
  32765. return this;
  32766. };
  32767. /**
  32768. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32769. * In other words, more vertices, no more indices and a single bigger VBO.
  32770. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32771. * @returns current mesh
  32772. */
  32773. Mesh.prototype.convertToUnIndexedMesh = function () {
  32774. var kinds = this.getVerticesDataKinds();
  32775. var vbs = {};
  32776. var data = {};
  32777. var newdata = {};
  32778. var kindIndex;
  32779. var kind;
  32780. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32781. kind = kinds[kindIndex];
  32782. var vertexBuffer = this.getVertexBuffer(kind);
  32783. vbs[kind] = vertexBuffer;
  32784. data[kind] = vbs[kind].getData();
  32785. newdata[kind] = [];
  32786. }
  32787. // Save previous submeshes
  32788. var previousSubmeshes = this.subMeshes.slice(0);
  32789. var indices = this.getIndices();
  32790. var totalIndices = this.getTotalIndices();
  32791. // Generating unique vertices per face
  32792. var index;
  32793. for (index = 0; index < totalIndices; index++) {
  32794. var vertexIndex = indices[index];
  32795. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32796. kind = kinds[kindIndex];
  32797. var stride = vbs[kind].getStrideSize();
  32798. for (var offset = 0; offset < stride; offset++) {
  32799. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32800. }
  32801. }
  32802. }
  32803. // Updating indices
  32804. for (index = 0; index < totalIndices; index += 3) {
  32805. indices[index] = index;
  32806. indices[index + 1] = index + 1;
  32807. indices[index + 2] = index + 2;
  32808. }
  32809. this.setIndices(indices);
  32810. // Updating vertex buffers
  32811. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32812. kind = kinds[kindIndex];
  32813. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32814. }
  32815. // Updating submeshes
  32816. this.releaseSubMeshes();
  32817. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32818. var previousOne = previousSubmeshes[submeshIndex];
  32819. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32820. }
  32821. this._unIndexed = true;
  32822. this.synchronizeInstances();
  32823. return this;
  32824. };
  32825. /**
  32826. * Inverses facet orientations.
  32827. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32828. * @param flipNormals will also inverts the normals
  32829. * @returns current mesh
  32830. */
  32831. Mesh.prototype.flipFaces = function (flipNormals) {
  32832. if (flipNormals === void 0) { flipNormals = false; }
  32833. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32834. var i;
  32835. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32836. for (i = 0; i < vertex_data.normals.length; i++) {
  32837. vertex_data.normals[i] *= -1;
  32838. }
  32839. }
  32840. if (vertex_data.indices) {
  32841. var temp;
  32842. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32843. // reassign indices
  32844. temp = vertex_data.indices[i + 1];
  32845. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32846. vertex_data.indices[i + 2] = temp;
  32847. }
  32848. }
  32849. vertex_data.applyToMesh(this);
  32850. return this;
  32851. };
  32852. // Instances
  32853. /**
  32854. * Creates a new InstancedMesh object from the mesh model.
  32855. * Warning : this method is not supported for Line mesh and LineSystem
  32856. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32857. * @param name defines the name of the new instance
  32858. * @returns a new InstancedMesh
  32859. */
  32860. Mesh.prototype.createInstance = function (name) {
  32861. return new BABYLON.InstancedMesh(name, this);
  32862. };
  32863. /**
  32864. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32865. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32866. * @returns the current mesh
  32867. */
  32868. Mesh.prototype.synchronizeInstances = function () {
  32869. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32870. var instance = this.instances[instanceIndex];
  32871. instance._syncSubMeshes();
  32872. }
  32873. return this;
  32874. };
  32875. /**
  32876. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32877. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32878. * This should be used together with the simplification to avoid disappearing triangles.
  32879. * @param successCallback an optional success callback to be called after the optimization finished.
  32880. * @returns the current mesh
  32881. */
  32882. Mesh.prototype.optimizeIndices = function (successCallback) {
  32883. var _this = this;
  32884. var indices = this.getIndices();
  32885. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32886. if (!positions || !indices) {
  32887. return this;
  32888. }
  32889. var vectorPositions = new Array();
  32890. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32891. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32892. }
  32893. var dupes = new Array();
  32894. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32895. var realPos = vectorPositions.length - 1 - iteration;
  32896. var testedPosition = vectorPositions[realPos];
  32897. for (var j = 0; j < realPos; ++j) {
  32898. var againstPosition = vectorPositions[j];
  32899. if (testedPosition.equals(againstPosition)) {
  32900. dupes[realPos] = j;
  32901. break;
  32902. }
  32903. }
  32904. }, function () {
  32905. for (var i = 0; i < indices.length; ++i) {
  32906. indices[i] = dupes[indices[i]] || indices[i];
  32907. }
  32908. //indices are now reordered
  32909. var originalSubMeshes = _this.subMeshes.slice(0);
  32910. _this.setIndices(indices);
  32911. _this.subMeshes = originalSubMeshes;
  32912. if (successCallback) {
  32913. successCallback(_this);
  32914. }
  32915. });
  32916. return this;
  32917. };
  32918. /**
  32919. * Serialize current mesh
  32920. * @param serializationObject defines the object which will receive the serialization data
  32921. */
  32922. Mesh.prototype.serialize = function (serializationObject) {
  32923. serializationObject.name = this.name;
  32924. serializationObject.id = this.id;
  32925. serializationObject.type = this.getClassName();
  32926. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32927. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32928. }
  32929. serializationObject.position = this.position.asArray();
  32930. if (this.rotationQuaternion) {
  32931. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32932. }
  32933. else if (this.rotation) {
  32934. serializationObject.rotation = this.rotation.asArray();
  32935. }
  32936. serializationObject.scaling = this.scaling.asArray();
  32937. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32938. serializationObject.isEnabled = this.isEnabled(false);
  32939. serializationObject.isVisible = this.isVisible;
  32940. serializationObject.infiniteDistance = this.infiniteDistance;
  32941. serializationObject.pickable = this.isPickable;
  32942. serializationObject.receiveShadows = this.receiveShadows;
  32943. serializationObject.billboardMode = this.billboardMode;
  32944. serializationObject.visibility = this.visibility;
  32945. serializationObject.checkCollisions = this.checkCollisions;
  32946. serializationObject.isBlocker = this.isBlocker;
  32947. // Parent
  32948. if (this.parent) {
  32949. serializationObject.parentId = this.parent.id;
  32950. }
  32951. // Geometry
  32952. serializationObject.isUnIndexed = this.isUnIndexed;
  32953. var geometry = this._geometry;
  32954. if (geometry) {
  32955. var geometryId = geometry.id;
  32956. serializationObject.geometryId = geometryId;
  32957. // SubMeshes
  32958. serializationObject.subMeshes = [];
  32959. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32960. var subMesh = this.subMeshes[subIndex];
  32961. serializationObject.subMeshes.push({
  32962. materialIndex: subMesh.materialIndex,
  32963. verticesStart: subMesh.verticesStart,
  32964. verticesCount: subMesh.verticesCount,
  32965. indexStart: subMesh.indexStart,
  32966. indexCount: subMesh.indexCount
  32967. });
  32968. }
  32969. }
  32970. // Material
  32971. if (this.material) {
  32972. serializationObject.materialId = this.material.id;
  32973. }
  32974. else {
  32975. this.material = null;
  32976. }
  32977. // Morph targets
  32978. if (this.morphTargetManager) {
  32979. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32980. }
  32981. // Skeleton
  32982. if (this.skeleton) {
  32983. serializationObject.skeletonId = this.skeleton.id;
  32984. }
  32985. // Physics
  32986. //TODO implement correct serialization for physics impostors.
  32987. var impostor = this.getPhysicsImpostor();
  32988. if (impostor) {
  32989. serializationObject.physicsMass = impostor.getParam("mass");
  32990. serializationObject.physicsFriction = impostor.getParam("friction");
  32991. serializationObject.physicsRestitution = impostor.getParam("mass");
  32992. serializationObject.physicsImpostor = impostor.type;
  32993. }
  32994. // Metadata
  32995. if (this.metadata) {
  32996. serializationObject.metadata = this.metadata;
  32997. }
  32998. // Instances
  32999. serializationObject.instances = [];
  33000. for (var index = 0; index < this.instances.length; index++) {
  33001. var instance = this.instances[index];
  33002. if (instance.doNotSerialize) {
  33003. continue;
  33004. }
  33005. var serializationInstance = {
  33006. name: instance.name,
  33007. id: instance.id,
  33008. position: instance.position.asArray(),
  33009. scaling: instance.scaling.asArray()
  33010. };
  33011. if (instance.parent) {
  33012. serializationInstance.parentId = instance.parent.id;
  33013. }
  33014. if (instance.rotationQuaternion) {
  33015. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33016. }
  33017. else if (instance.rotation) {
  33018. serializationInstance.rotation = instance.rotation.asArray();
  33019. }
  33020. serializationObject.instances.push(serializationInstance);
  33021. // Animations
  33022. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33023. serializationInstance.ranges = instance.serializeAnimationRanges();
  33024. }
  33025. //
  33026. // Animations
  33027. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33028. serializationObject.ranges = this.serializeAnimationRanges();
  33029. // Layer mask
  33030. serializationObject.layerMask = this.layerMask;
  33031. // Alpha
  33032. serializationObject.alphaIndex = this.alphaIndex;
  33033. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33034. // Overlay
  33035. serializationObject.overlayAlpha = this.overlayAlpha;
  33036. serializationObject.overlayColor = this.overlayColor.asArray();
  33037. serializationObject.renderOverlay = this.renderOverlay;
  33038. // Fog
  33039. serializationObject.applyFog = this.applyFog;
  33040. // Action Manager
  33041. if (this.actionManager) {
  33042. serializationObject.actions = this.actionManager.serialize(this.name);
  33043. }
  33044. };
  33045. /** @hidden */
  33046. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33047. if (!this.geometry) {
  33048. return;
  33049. }
  33050. this._markSubMeshesAsAttributesDirty();
  33051. var morphTargetManager = this._morphTargetManager;
  33052. if (morphTargetManager && morphTargetManager.vertexCount) {
  33053. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33054. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33055. this.morphTargetManager = null;
  33056. return;
  33057. }
  33058. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33059. var morphTarget = morphTargetManager.getActiveTarget(index);
  33060. var positions = morphTarget.getPositions();
  33061. if (!positions) {
  33062. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33063. return;
  33064. }
  33065. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33066. var normals = morphTarget.getNormals();
  33067. if (normals) {
  33068. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33069. }
  33070. var tangents = morphTarget.getTangents();
  33071. if (tangents) {
  33072. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33073. }
  33074. }
  33075. }
  33076. else {
  33077. var index = 0;
  33078. // Positions
  33079. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33080. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33081. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33082. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33083. }
  33084. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33085. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33086. }
  33087. index++;
  33088. }
  33089. }
  33090. };
  33091. // Statics
  33092. /**
  33093. * Returns a new Mesh object parsed from the source provided.
  33094. * @param parsedMesh is the source
  33095. * @param scene defines the hosting scene
  33096. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33097. * @returns a new Mesh
  33098. */
  33099. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33100. var mesh;
  33101. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33102. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33103. }
  33104. else {
  33105. mesh = new Mesh(parsedMesh.name, scene);
  33106. }
  33107. mesh.id = parsedMesh.id;
  33108. if (BABYLON.Tags) {
  33109. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33110. }
  33111. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33112. if (parsedMesh.metadata !== undefined) {
  33113. mesh.metadata = parsedMesh.metadata;
  33114. }
  33115. if (parsedMesh.rotationQuaternion) {
  33116. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33117. }
  33118. else if (parsedMesh.rotation) {
  33119. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33120. }
  33121. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33122. if (parsedMesh.localMatrix) {
  33123. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33124. }
  33125. else if (parsedMesh.pivotMatrix) {
  33126. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33127. }
  33128. mesh.setEnabled(parsedMesh.isEnabled);
  33129. mesh.isVisible = parsedMesh.isVisible;
  33130. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33131. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33132. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33133. if (parsedMesh.applyFog !== undefined) {
  33134. mesh.applyFog = parsedMesh.applyFog;
  33135. }
  33136. if (parsedMesh.pickable !== undefined) {
  33137. mesh.isPickable = parsedMesh.pickable;
  33138. }
  33139. if (parsedMesh.alphaIndex !== undefined) {
  33140. mesh.alphaIndex = parsedMesh.alphaIndex;
  33141. }
  33142. mesh.receiveShadows = parsedMesh.receiveShadows;
  33143. mesh.billboardMode = parsedMesh.billboardMode;
  33144. if (parsedMesh.visibility !== undefined) {
  33145. mesh.visibility = parsedMesh.visibility;
  33146. }
  33147. mesh.checkCollisions = parsedMesh.checkCollisions;
  33148. if (parsedMesh.isBlocker !== undefined) {
  33149. mesh.isBlocker = parsedMesh.isBlocker;
  33150. }
  33151. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33152. // freezeWorldMatrix
  33153. if (parsedMesh.freezeWorldMatrix) {
  33154. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33155. }
  33156. // Parent
  33157. if (parsedMesh.parentId) {
  33158. mesh._waitingParentId = parsedMesh.parentId;
  33159. }
  33160. // Actions
  33161. if (parsedMesh.actions !== undefined) {
  33162. mesh._waitingActions = parsedMesh.actions;
  33163. }
  33164. // Overlay
  33165. if (parsedMesh.overlayAlpha !== undefined) {
  33166. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33167. }
  33168. if (parsedMesh.overlayColor !== undefined) {
  33169. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33170. }
  33171. if (parsedMesh.renderOverlay !== undefined) {
  33172. mesh.renderOverlay = parsedMesh.renderOverlay;
  33173. }
  33174. // Geometry
  33175. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33176. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33177. if (parsedMesh.delayLoadingFile) {
  33178. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33179. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33180. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33181. if (parsedMesh._binaryInfo) {
  33182. mesh._binaryInfo = parsedMesh._binaryInfo;
  33183. }
  33184. mesh._delayInfo = [];
  33185. if (parsedMesh.hasUVs) {
  33186. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33187. }
  33188. if (parsedMesh.hasUVs2) {
  33189. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33190. }
  33191. if (parsedMesh.hasUVs3) {
  33192. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33193. }
  33194. if (parsedMesh.hasUVs4) {
  33195. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33196. }
  33197. if (parsedMesh.hasUVs5) {
  33198. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33199. }
  33200. if (parsedMesh.hasUVs6) {
  33201. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33202. }
  33203. if (parsedMesh.hasColors) {
  33204. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33205. }
  33206. if (parsedMesh.hasMatricesIndices) {
  33207. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33208. }
  33209. if (parsedMesh.hasMatricesWeights) {
  33210. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33211. }
  33212. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33213. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33214. mesh._checkDelayState();
  33215. }
  33216. }
  33217. else {
  33218. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33219. }
  33220. // Material
  33221. if (parsedMesh.materialId) {
  33222. mesh.setMaterialByID(parsedMesh.materialId);
  33223. }
  33224. else {
  33225. mesh.material = null;
  33226. }
  33227. // Morph targets
  33228. if (parsedMesh.morphTargetManagerId > -1) {
  33229. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33230. }
  33231. // Skeleton
  33232. if (parsedMesh.skeletonId > -1) {
  33233. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33234. if (parsedMesh.numBoneInfluencers) {
  33235. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33236. }
  33237. }
  33238. // Animations
  33239. if (parsedMesh.animations) {
  33240. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33241. var parsedAnimation = parsedMesh.animations[animationIndex];
  33242. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33243. }
  33244. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33245. }
  33246. if (parsedMesh.autoAnimate) {
  33247. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33248. }
  33249. // Layer Mask
  33250. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33251. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33252. }
  33253. else {
  33254. mesh.layerMask = 0x0FFFFFFF;
  33255. }
  33256. // Physics
  33257. if (parsedMesh.physicsImpostor) {
  33258. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33259. mass: parsedMesh.physicsMass,
  33260. friction: parsedMesh.physicsFriction,
  33261. restitution: parsedMesh.physicsRestitution
  33262. }, scene);
  33263. }
  33264. // Instances
  33265. if (parsedMesh.instances) {
  33266. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33267. var parsedInstance = parsedMesh.instances[index];
  33268. var instance = mesh.createInstance(parsedInstance.name);
  33269. if (parsedInstance.id) {
  33270. instance.id = parsedInstance.id;
  33271. }
  33272. if (BABYLON.Tags) {
  33273. if (parsedInstance.tags) {
  33274. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33275. }
  33276. else {
  33277. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33278. }
  33279. }
  33280. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33281. if (parsedInstance.parentId) {
  33282. instance._waitingParentId = parsedInstance.parentId;
  33283. }
  33284. if (parsedInstance.rotationQuaternion) {
  33285. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33286. }
  33287. else if (parsedInstance.rotation) {
  33288. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33289. }
  33290. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33291. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33292. instance.checkCollisions = parsedInstance.checkCollisions;
  33293. }
  33294. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33295. instance.isPickable = parsedInstance.pickable;
  33296. }
  33297. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33298. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33299. }
  33300. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33301. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33302. }
  33303. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33304. instance.alphaIndex = parsedInstance.alphaIndex;
  33305. }
  33306. // Physics
  33307. if (parsedInstance.physicsImpostor) {
  33308. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33309. mass: parsedInstance.physicsMass,
  33310. friction: parsedInstance.physicsFriction,
  33311. restitution: parsedInstance.physicsRestitution
  33312. }, scene);
  33313. }
  33314. // Animation
  33315. if (parsedInstance.animations) {
  33316. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33317. parsedAnimation = parsedInstance.animations[animationIndex];
  33318. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33319. }
  33320. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33321. if (parsedInstance.autoAnimate) {
  33322. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33323. }
  33324. }
  33325. }
  33326. }
  33327. return mesh;
  33328. };
  33329. /**
  33330. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33331. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33332. * @param name defines the name of the mesh to create
  33333. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33334. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33335. * @param closePath creates a seam between the first and the last points of each path of the path array
  33336. * @param offset is taken in account only if the `pathArray` is containing a single path
  33337. * @param scene defines the hosting scene
  33338. * @param updatable defines if the mesh must be flagged as updatable
  33339. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33340. * @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)
  33341. * @returns a new Mesh
  33342. */
  33343. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33344. if (closeArray === void 0) { closeArray = false; }
  33345. if (updatable === void 0) { updatable = false; }
  33346. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33347. pathArray: pathArray,
  33348. closeArray: closeArray,
  33349. closePath: closePath,
  33350. offset: offset,
  33351. updatable: updatable,
  33352. sideOrientation: sideOrientation,
  33353. instance: instance
  33354. }, scene);
  33355. };
  33356. /**
  33357. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33358. * @param name defines the name of the mesh to create
  33359. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33360. * @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
  33361. * @param scene defines the hosting scene
  33362. * @param updatable defines if the mesh must be flagged as updatable
  33363. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33364. * @returns a new Mesh
  33365. */
  33366. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33367. if (scene === void 0) { scene = null; }
  33368. var options = {
  33369. radius: radius,
  33370. tessellation: tessellation,
  33371. sideOrientation: sideOrientation,
  33372. updatable: updatable
  33373. };
  33374. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33375. };
  33376. /**
  33377. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33378. * @param name defines the name of the mesh to create
  33379. * @param size sets the size (float) of each box side (default 1)
  33380. * @param scene defines the hosting scene
  33381. * @param updatable defines if the mesh must be flagged as updatable
  33382. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33383. * @returns a new Mesh
  33384. */
  33385. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33386. if (scene === void 0) { scene = null; }
  33387. var options = {
  33388. size: size,
  33389. sideOrientation: sideOrientation,
  33390. updatable: updatable
  33391. };
  33392. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33393. };
  33394. /**
  33395. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33396. * @param name defines the name of the mesh to create
  33397. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33398. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33399. * @param scene defines the hosting scene
  33400. * @param updatable defines if the mesh must be flagged as updatable
  33401. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33402. * @returns a new Mesh
  33403. */
  33404. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33405. var options = {
  33406. segments: segments,
  33407. diameterX: diameter,
  33408. diameterY: diameter,
  33409. diameterZ: diameter,
  33410. sideOrientation: sideOrientation,
  33411. updatable: updatable
  33412. };
  33413. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33414. };
  33415. /**
  33416. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33417. * @param name defines the name of the mesh to create
  33418. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33419. * @param diameterTop set the top cap diameter (floats, default 1)
  33420. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33421. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33422. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33423. * @param scene defines the hosting scene
  33424. * @param updatable defines if the mesh must be flagged as updatable
  33425. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33426. * @returns a new Mesh
  33427. */
  33428. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33429. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33430. if (scene !== undefined) {
  33431. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33432. updatable = scene;
  33433. }
  33434. scene = subdivisions;
  33435. subdivisions = 1;
  33436. }
  33437. var options = {
  33438. height: height,
  33439. diameterTop: diameterTop,
  33440. diameterBottom: diameterBottom,
  33441. tessellation: tessellation,
  33442. subdivisions: subdivisions,
  33443. sideOrientation: sideOrientation,
  33444. updatable: updatable
  33445. };
  33446. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33447. };
  33448. // Torus (Code from SharpDX.org)
  33449. /**
  33450. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33451. * @param name defines the name of the mesh to create
  33452. * @param diameter sets the diameter size (float) of the torus (default 1)
  33453. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33454. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33455. * @param scene defines the hosting scene
  33456. * @param updatable defines if the mesh must be flagged as updatable
  33457. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33458. * @returns a new Mesh
  33459. */
  33460. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33461. var options = {
  33462. diameter: diameter,
  33463. thickness: thickness,
  33464. tessellation: tessellation,
  33465. sideOrientation: sideOrientation,
  33466. updatable: updatable
  33467. };
  33468. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33469. };
  33470. /**
  33471. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33472. * @param name defines the name of the mesh to create
  33473. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33474. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33475. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33476. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33477. * @param p the number of windings on X axis (positive integers, default 2)
  33478. * @param q the number of windings on Y axis (positive integers, default 3)
  33479. * @param scene defines the hosting scene
  33480. * @param updatable defines if the mesh must be flagged as updatable
  33481. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33482. * @returns a new Mesh
  33483. */
  33484. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33485. var options = {
  33486. radius: radius,
  33487. tube: tube,
  33488. radialSegments: radialSegments,
  33489. tubularSegments: tubularSegments,
  33490. p: p,
  33491. q: q,
  33492. sideOrientation: sideOrientation,
  33493. updatable: updatable
  33494. };
  33495. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33496. };
  33497. /**
  33498. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33499. * @param name defines the name of the mesh to create
  33500. * @param points is an array successive Vector3
  33501. * @param scene defines the hosting scene
  33502. * @param updatable defines if the mesh must be flagged as updatable
  33503. * @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).
  33504. * @returns a new Mesh
  33505. */
  33506. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33507. if (scene === void 0) { scene = null; }
  33508. if (updatable === void 0) { updatable = false; }
  33509. if (instance === void 0) { instance = null; }
  33510. var options = {
  33511. points: points,
  33512. updatable: updatable,
  33513. instance: instance
  33514. };
  33515. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33516. };
  33517. /**
  33518. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33519. * @param name defines the name of the mesh to create
  33520. * @param points is an array successive Vector3
  33521. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33522. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33523. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33524. * @param scene defines the hosting scene
  33525. * @param updatable defines if the mesh must be flagged as updatable
  33526. * @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)
  33527. * @returns a new Mesh
  33528. */
  33529. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33530. if (scene === void 0) { scene = null; }
  33531. var options = {
  33532. points: points,
  33533. dashSize: dashSize,
  33534. gapSize: gapSize,
  33535. dashNb: dashNb,
  33536. updatable: updatable,
  33537. instance: instance
  33538. };
  33539. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33540. };
  33541. /**
  33542. * Creates a polygon mesh.
  33543. * Please consider using the same method from the MeshBuilder class instead.
  33544. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33545. * 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.
  33546. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33548. * Remember you can only change the shape positions, not their number when updating a polygon.
  33549. */
  33550. /**
  33551. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33552. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33553. * @param name defines the name of the mesh to create
  33554. * @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
  33555. * @param scene defines the hosting scene
  33556. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33557. * @param updatable defines if the mesh must be flagged as updatable
  33558. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33559. * @returns a new Mesh
  33560. */
  33561. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33562. var options = {
  33563. shape: shape,
  33564. holes: holes,
  33565. updatable: updatable,
  33566. sideOrientation: sideOrientation
  33567. };
  33568. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33569. };
  33570. /**
  33571. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33572. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33573. * @param name defines the name of the mesh to create
  33574. * @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
  33575. * @param depth defines the height of extrusion
  33576. * @param scene defines the hosting scene
  33577. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33578. * @param updatable defines if the mesh must be flagged as updatable
  33579. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33580. * @returns a new Mesh
  33581. */
  33582. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33583. var options = {
  33584. shape: shape,
  33585. holes: holes,
  33586. depth: depth,
  33587. updatable: updatable,
  33588. sideOrientation: sideOrientation
  33589. };
  33590. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33591. };
  33592. /**
  33593. * Creates an extruded shape mesh.
  33594. * 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
  33595. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33596. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33597. * @param name defines the name of the mesh to create
  33598. * @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
  33599. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33600. * @param scale is the value to scale the shape
  33601. * @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
  33602. * @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
  33603. * @param scene defines the hosting scene
  33604. * @param updatable defines if the mesh must be flagged as updatable
  33605. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33606. * @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)
  33607. * @returns a new Mesh
  33608. */
  33609. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33610. if (scene === void 0) { scene = null; }
  33611. var options = {
  33612. shape: shape,
  33613. path: path,
  33614. scale: scale,
  33615. rotation: rotation,
  33616. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33617. sideOrientation: sideOrientation,
  33618. instance: instance,
  33619. updatable: updatable
  33620. };
  33621. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33622. };
  33623. /**
  33624. * Creates an custom extruded shape mesh.
  33625. * The custom extrusion is a parametric shape.
  33626. * It has no predefined shape. Its final shape will depend on the input parameters.
  33627. * Please consider using the same method from the MeshBuilder class instead
  33628. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33629. * @param name defines the name of the mesh to create
  33630. * @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
  33631. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33632. * @param scaleFunction is a custom Javascript function called on each path point
  33633. * @param rotationFunction is a custom Javascript function called on each path point
  33634. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33635. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33636. * @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
  33637. * @param scene defines the hosting scene
  33638. * @param updatable defines if the mesh must be flagged as updatable
  33639. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33640. * @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)
  33641. * @returns a new Mesh
  33642. */
  33643. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33644. var options = {
  33645. shape: shape,
  33646. path: path,
  33647. scaleFunction: scaleFunction,
  33648. rotationFunction: rotationFunction,
  33649. ribbonCloseArray: ribbonCloseArray,
  33650. ribbonClosePath: ribbonClosePath,
  33651. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33652. sideOrientation: sideOrientation,
  33653. instance: instance,
  33654. updatable: updatable
  33655. };
  33656. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33657. };
  33658. /**
  33659. * Creates lathe mesh.
  33660. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33661. * Please consider using the same method from the MeshBuilder class instead
  33662. * @param name defines the name of the mesh to create
  33663. * @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
  33664. * @param radius is the radius value of the lathe
  33665. * @param tessellation is the side number of the lathe.
  33666. * @param scene defines the hosting scene
  33667. * @param updatable defines if the mesh must be flagged as updatable
  33668. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33669. * @returns a new Mesh
  33670. */
  33671. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33672. var options = {
  33673. shape: shape,
  33674. radius: radius,
  33675. tessellation: tessellation,
  33676. sideOrientation: sideOrientation,
  33677. updatable: updatable
  33678. };
  33679. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33680. };
  33681. /**
  33682. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33683. * @param name defines the name of the mesh to create
  33684. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33685. * @param scene defines the hosting scene
  33686. * @param updatable defines if the mesh must be flagged as updatable
  33687. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33688. * @returns a new Mesh
  33689. */
  33690. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33691. var options = {
  33692. size: size,
  33693. width: size,
  33694. height: size,
  33695. sideOrientation: sideOrientation,
  33696. updatable: updatable
  33697. };
  33698. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33699. };
  33700. /**
  33701. * Creates a ground mesh.
  33702. * Please consider using the same method from the MeshBuilder class instead
  33703. * @param name defines the name of the mesh to create
  33704. * @param width set the width of the ground
  33705. * @param height set the height of the ground
  33706. * @param subdivisions sets the number of subdivisions per side
  33707. * @param scene defines the hosting scene
  33708. * @param updatable defines if the mesh must be flagged as updatable
  33709. * @returns a new Mesh
  33710. */
  33711. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33712. var options = {
  33713. width: width,
  33714. height: height,
  33715. subdivisions: subdivisions,
  33716. updatable: updatable
  33717. };
  33718. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33719. };
  33720. /**
  33721. * Creates a tiled ground mesh.
  33722. * Please consider using the same method from the MeshBuilder class instead
  33723. * @param name defines the name of the mesh to create
  33724. * @param xmin set the ground minimum X coordinate
  33725. * @param zmin set the ground minimum Y coordinate
  33726. * @param xmax set the ground maximum X coordinate
  33727. * @param zmax set the ground maximum Z coordinate
  33728. * @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
  33729. * @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
  33730. * @param scene defines the hosting scene
  33731. * @param updatable defines if the mesh must be flagged as updatable
  33732. * @returns a new Mesh
  33733. */
  33734. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33735. var options = {
  33736. xmin: xmin,
  33737. zmin: zmin,
  33738. xmax: xmax,
  33739. zmax: zmax,
  33740. subdivisions: subdivisions,
  33741. precision: precision,
  33742. updatable: updatable
  33743. };
  33744. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33745. };
  33746. /**
  33747. * Creates a ground mesh from a height map.
  33748. * Please consider using the same method from the MeshBuilder class instead
  33749. * @see http://doc.babylonjs.com/babylon101/height_map
  33750. * @param name defines the name of the mesh to create
  33751. * @param url sets the URL of the height map image resource
  33752. * @param width set the ground width size
  33753. * @param height set the ground height size
  33754. * @param subdivisions sets the number of subdivision per side
  33755. * @param minHeight is the minimum altitude on the ground
  33756. * @param maxHeight is the maximum altitude on the ground
  33757. * @param scene defines the hosting scene
  33758. * @param updatable defines if the mesh must be flagged as updatable
  33759. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33760. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33761. * @returns a new Mesh
  33762. */
  33763. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33764. var options = {
  33765. width: width,
  33766. height: height,
  33767. subdivisions: subdivisions,
  33768. minHeight: minHeight,
  33769. maxHeight: maxHeight,
  33770. updatable: updatable,
  33771. onReady: onReady,
  33772. alphaFilter: alphaFilter
  33773. };
  33774. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33775. };
  33776. /**
  33777. * Creates a tube mesh.
  33778. * The tube is a parametric shape.
  33779. * It has no predefined shape. Its final shape will depend on the input parameters.
  33780. * Please consider using the same method from the MeshBuilder class instead
  33781. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33782. * @param name defines the name of the mesh to create
  33783. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33784. * @param radius sets the tube radius size
  33785. * @param tessellation is the number of sides on the tubular surface
  33786. * @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
  33787. * @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
  33788. * @param scene defines the hosting scene
  33789. * @param updatable defines if the mesh must be flagged as updatable
  33790. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33791. * @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)
  33792. * @returns a new Mesh
  33793. */
  33794. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33795. var options = {
  33796. path: path,
  33797. radius: radius,
  33798. tessellation: tessellation,
  33799. radiusFunction: radiusFunction,
  33800. arc: 1,
  33801. cap: cap,
  33802. updatable: updatable,
  33803. sideOrientation: sideOrientation,
  33804. instance: instance
  33805. };
  33806. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33807. };
  33808. /**
  33809. * Creates a polyhedron mesh.
  33810. * Please consider using the same method from the MeshBuilder class instead.
  33811. * * 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
  33812. * * The parameter `size` (positive float, default 1) sets the polygon size
  33813. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33814. * * 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`
  33815. * * 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
  33816. * * 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)`)
  33817. * * 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
  33818. * * 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
  33819. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33820. * * 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
  33821. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33822. * @param name defines the name of the mesh to create
  33823. * @param options defines the options used to create the mesh
  33824. * @param scene defines the hosting scene
  33825. * @returns a new Mesh
  33826. */
  33827. Mesh.CreatePolyhedron = function (name, options, scene) {
  33828. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33829. };
  33830. /**
  33831. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33832. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33833. * * 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`)
  33834. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33835. * * 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
  33836. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33837. * * 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
  33838. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33839. * @param name defines the name of the mesh
  33840. * @param options defines the options used to create the mesh
  33841. * @param scene defines the hosting scene
  33842. * @returns a new Mesh
  33843. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33844. */
  33845. Mesh.CreateIcoSphere = function (name, options, scene) {
  33846. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33847. };
  33848. /**
  33849. * Creates a decal mesh.
  33850. * Please consider using the same method from the MeshBuilder class instead.
  33851. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33852. * @param name defines the name of the mesh
  33853. * @param sourceMesh defines the mesh receiving the decal
  33854. * @param position sets the position of the decal in world coordinates
  33855. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33856. * @param size sets the decal scaling
  33857. * @param angle sets the angle to rotate the decal
  33858. * @returns a new Mesh
  33859. */
  33860. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33861. var options = {
  33862. position: position,
  33863. normal: normal,
  33864. size: size,
  33865. angle: angle
  33866. };
  33867. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33868. };
  33869. // Skeletons
  33870. /**
  33871. * Prepare internal position array for software CPU skinning
  33872. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33873. */
  33874. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33875. if (!this._sourcePositions) {
  33876. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33877. if (!source) {
  33878. return this._sourcePositions;
  33879. }
  33880. this._sourcePositions = new Float32Array(source);
  33881. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33882. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33883. }
  33884. }
  33885. return this._sourcePositions;
  33886. };
  33887. /**
  33888. * Prepare internal normal array for software CPU skinning
  33889. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33890. */
  33891. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33892. if (!this._sourceNormals) {
  33893. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33894. if (!source) {
  33895. return this._sourceNormals;
  33896. }
  33897. this._sourceNormals = new Float32Array(source);
  33898. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33899. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33900. }
  33901. }
  33902. return this._sourceNormals;
  33903. };
  33904. /**
  33905. * Updates the vertex buffer by applying transformation from the bones
  33906. * @param skeleton defines the skeleton to apply to current mesh
  33907. * @returns the current mesh
  33908. */
  33909. Mesh.prototype.applySkeleton = function (skeleton) {
  33910. if (!this.geometry) {
  33911. return this;
  33912. }
  33913. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33914. return this;
  33915. }
  33916. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33917. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33918. return this;
  33919. }
  33920. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33921. return this;
  33922. }
  33923. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33924. return this;
  33925. }
  33926. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33927. return this;
  33928. }
  33929. if (!this._sourcePositions) {
  33930. var submeshes = this.subMeshes.slice();
  33931. this.setPositionsForCPUSkinning();
  33932. this.subMeshes = submeshes;
  33933. }
  33934. if (!this._sourceNormals) {
  33935. this.setNormalsForCPUSkinning();
  33936. }
  33937. // positionsData checks for not being Float32Array will only pass at most once
  33938. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33939. if (!positionsData) {
  33940. return this;
  33941. }
  33942. if (!(positionsData instanceof Float32Array)) {
  33943. positionsData = new Float32Array(positionsData);
  33944. }
  33945. // normalsData checks for not being Float32Array will only pass at most once
  33946. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33947. if (!normalsData) {
  33948. return this;
  33949. }
  33950. if (!(normalsData instanceof Float32Array)) {
  33951. normalsData = new Float32Array(normalsData);
  33952. }
  33953. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33954. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33955. if (!matricesWeightsData || !matricesIndicesData) {
  33956. return this;
  33957. }
  33958. var needExtras = this.numBoneInfluencers > 4;
  33959. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33960. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33961. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33962. var tempVector3 = BABYLON.Vector3.Zero();
  33963. var finalMatrix = new BABYLON.Matrix();
  33964. var tempMatrix = new BABYLON.Matrix();
  33965. var matWeightIdx = 0;
  33966. var inf;
  33967. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33968. var weight;
  33969. for (inf = 0; inf < 4; inf++) {
  33970. weight = matricesWeightsData[matWeightIdx + inf];
  33971. if (weight > 0) {
  33972. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33973. finalMatrix.addToSelf(tempMatrix);
  33974. }
  33975. }
  33976. if (needExtras) {
  33977. for (inf = 0; inf < 4; inf++) {
  33978. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33979. if (weight > 0) {
  33980. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33981. finalMatrix.addToSelf(tempMatrix);
  33982. }
  33983. }
  33984. }
  33985. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33986. tempVector3.toArray(positionsData, index);
  33987. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33988. tempVector3.toArray(normalsData, index);
  33989. finalMatrix.reset();
  33990. }
  33991. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33992. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33993. return this;
  33994. };
  33995. // Tools
  33996. /**
  33997. * 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
  33998. * @param meshes defines the list of meshes to scan
  33999. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34000. */
  34001. Mesh.MinMax = function (meshes) {
  34002. var minVector = null;
  34003. var maxVector = null;
  34004. meshes.forEach(function (mesh, index, array) {
  34005. var boundingInfo = mesh.getBoundingInfo();
  34006. var boundingBox = boundingInfo.boundingBox;
  34007. if (!minVector || !maxVector) {
  34008. minVector = boundingBox.minimumWorld;
  34009. maxVector = boundingBox.maximumWorld;
  34010. }
  34011. else {
  34012. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34013. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34014. }
  34015. });
  34016. if (!minVector || !maxVector) {
  34017. return {
  34018. min: BABYLON.Vector3.Zero(),
  34019. max: BABYLON.Vector3.Zero()
  34020. };
  34021. }
  34022. return {
  34023. min: minVector,
  34024. max: maxVector
  34025. };
  34026. };
  34027. /**
  34028. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34029. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34030. * @returns a vector3
  34031. */
  34032. Mesh.Center = function (meshesOrMinMaxVector) {
  34033. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34034. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34035. };
  34036. /**
  34037. * Merge the array of meshes into a single mesh for performance reasons.
  34038. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34039. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34040. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34041. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34042. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34043. * @returns a new mesh
  34044. */
  34045. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34046. if (disposeSource === void 0) { disposeSource = true; }
  34047. var index;
  34048. if (!allow32BitsIndices) {
  34049. var totalVertices = 0;
  34050. // Counting vertices
  34051. for (index = 0; index < meshes.length; index++) {
  34052. if (meshes[index]) {
  34053. totalVertices += meshes[index].getTotalVertices();
  34054. if (totalVertices > 65536) {
  34055. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34056. return null;
  34057. }
  34058. }
  34059. }
  34060. }
  34061. // Merge
  34062. var vertexData = null;
  34063. var otherVertexData;
  34064. var indiceArray = new Array();
  34065. var source = null;
  34066. for (index = 0; index < meshes.length; index++) {
  34067. if (meshes[index]) {
  34068. var wm = meshes[index].computeWorldMatrix(true);
  34069. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34070. otherVertexData.transform(wm);
  34071. if (vertexData) {
  34072. vertexData.merge(otherVertexData, allow32BitsIndices);
  34073. }
  34074. else {
  34075. vertexData = otherVertexData;
  34076. source = meshes[index];
  34077. }
  34078. if (subdivideWithSubMeshes) {
  34079. indiceArray.push(meshes[index].getTotalIndices());
  34080. }
  34081. }
  34082. }
  34083. source = source;
  34084. if (!meshSubclass) {
  34085. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34086. }
  34087. vertexData.applyToMesh(meshSubclass);
  34088. // Setting properties
  34089. meshSubclass.material = source.material;
  34090. meshSubclass.checkCollisions = source.checkCollisions;
  34091. // Cleaning
  34092. if (disposeSource) {
  34093. for (index = 0; index < meshes.length; index++) {
  34094. if (meshes[index]) {
  34095. meshes[index].dispose();
  34096. }
  34097. }
  34098. }
  34099. // Subdivide
  34100. if (subdivideWithSubMeshes) {
  34101. //-- removal of global submesh
  34102. meshSubclass.releaseSubMeshes();
  34103. index = 0;
  34104. var offset = 0;
  34105. //-- apply subdivision according to index table
  34106. while (index < indiceArray.length) {
  34107. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34108. offset += indiceArray[index];
  34109. index++;
  34110. }
  34111. }
  34112. return meshSubclass;
  34113. };
  34114. // Consts
  34115. /**
  34116. * Mesh side orientation : usually the external or front surface
  34117. */
  34118. Mesh.FRONTSIDE = 0;
  34119. /**
  34120. * Mesh side orientation : usually the internal or back surface
  34121. */
  34122. Mesh.BACKSIDE = 1;
  34123. /**
  34124. * Mesh side orientation : both internal and external or front and back surfaces
  34125. */
  34126. Mesh.DOUBLESIDE = 2;
  34127. /**
  34128. * Mesh side orientation : by default, `FRONTSIDE`
  34129. */
  34130. Mesh.DEFAULTSIDE = 0;
  34131. /**
  34132. * Mesh cap setting : no cap
  34133. */
  34134. Mesh.NO_CAP = 0;
  34135. /**
  34136. * Mesh cap setting : one cap at the beginning of the mesh
  34137. */
  34138. Mesh.CAP_START = 1;
  34139. /**
  34140. * Mesh cap setting : one cap at the end of the mesh
  34141. */
  34142. Mesh.CAP_END = 2;
  34143. /**
  34144. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34145. */
  34146. Mesh.CAP_ALL = 3;
  34147. return Mesh;
  34148. }(BABYLON.AbstractMesh));
  34149. BABYLON.Mesh = Mesh;
  34150. })(BABYLON || (BABYLON = {}));
  34151. //# sourceMappingURL=babylon.mesh.js.map
  34152. var BABYLON;
  34153. (function (BABYLON) {
  34154. var BaseSubMesh = /** @class */ (function () {
  34155. function BaseSubMesh() {
  34156. }
  34157. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34158. get: function () {
  34159. return this._materialEffect;
  34160. },
  34161. enumerable: true,
  34162. configurable: true
  34163. });
  34164. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34165. if (defines === void 0) { defines = null; }
  34166. if (this._materialEffect === effect) {
  34167. if (!effect) {
  34168. this._materialDefines = null;
  34169. }
  34170. return;
  34171. }
  34172. this._materialDefines = defines;
  34173. this._materialEffect = effect;
  34174. };
  34175. return BaseSubMesh;
  34176. }());
  34177. BABYLON.BaseSubMesh = BaseSubMesh;
  34178. var SubMesh = /** @class */ (function (_super) {
  34179. __extends(SubMesh, _super);
  34180. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34181. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34182. var _this = _super.call(this) || this;
  34183. _this.materialIndex = materialIndex;
  34184. _this.verticesStart = verticesStart;
  34185. _this.verticesCount = verticesCount;
  34186. _this.indexStart = indexStart;
  34187. _this.indexCount = indexCount;
  34188. /** @hidden */
  34189. _this._renderId = 0;
  34190. _this._mesh = mesh;
  34191. _this._renderingMesh = renderingMesh || mesh;
  34192. mesh.subMeshes.push(_this);
  34193. _this._trianglePlanes = [];
  34194. _this._id = mesh.subMeshes.length - 1;
  34195. if (createBoundingBox) {
  34196. _this.refreshBoundingInfo();
  34197. mesh.computeWorldMatrix(true);
  34198. }
  34199. return _this;
  34200. }
  34201. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34202. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34203. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34204. };
  34205. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34206. get: function () {
  34207. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34208. },
  34209. enumerable: true,
  34210. configurable: true
  34211. });
  34212. /**
  34213. * Returns the submesh BoudingInfo object.
  34214. */
  34215. SubMesh.prototype.getBoundingInfo = function () {
  34216. if (this.IsGlobal) {
  34217. return this._mesh.getBoundingInfo();
  34218. }
  34219. return this._boundingInfo;
  34220. };
  34221. /**
  34222. * Sets the submesh BoundingInfo.
  34223. * Return the SubMesh.
  34224. */
  34225. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34226. this._boundingInfo = boundingInfo;
  34227. return this;
  34228. };
  34229. /**
  34230. * Returns the mesh of the current submesh.
  34231. */
  34232. SubMesh.prototype.getMesh = function () {
  34233. return this._mesh;
  34234. };
  34235. /**
  34236. * Returns the rendering mesh of the submesh.
  34237. */
  34238. SubMesh.prototype.getRenderingMesh = function () {
  34239. return this._renderingMesh;
  34240. };
  34241. /**
  34242. * Returns the submesh material.
  34243. */
  34244. SubMesh.prototype.getMaterial = function () {
  34245. var rootMaterial = this._renderingMesh.material;
  34246. if (rootMaterial === null || rootMaterial === undefined) {
  34247. return this._mesh.getScene().defaultMaterial;
  34248. }
  34249. else if (rootMaterial.getSubMaterial) {
  34250. var multiMaterial = rootMaterial;
  34251. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34252. if (this._currentMaterial !== effectiveMaterial) {
  34253. this._currentMaterial = effectiveMaterial;
  34254. this._materialDefines = null;
  34255. }
  34256. return effectiveMaterial;
  34257. }
  34258. return rootMaterial;
  34259. };
  34260. // Methods
  34261. /**
  34262. * Sets a new updated BoundingInfo object to the submesh.
  34263. * Returns the SubMesh.
  34264. */
  34265. SubMesh.prototype.refreshBoundingInfo = function () {
  34266. this._lastColliderWorldVertices = null;
  34267. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34268. return this;
  34269. }
  34270. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34271. if (!data) {
  34272. this._boundingInfo = this._mesh.getBoundingInfo();
  34273. return this;
  34274. }
  34275. var indices = this._renderingMesh.getIndices();
  34276. var extend;
  34277. //is this the only submesh?
  34278. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34279. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34280. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34281. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34282. }
  34283. else {
  34284. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34285. }
  34286. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34287. return this;
  34288. };
  34289. /** @hidden */
  34290. SubMesh.prototype._checkCollision = function (collider) {
  34291. var boundingInfo = this.getBoundingInfo();
  34292. return boundingInfo._checkCollision(collider);
  34293. };
  34294. /**
  34295. * Updates the submesh BoundingInfo.
  34296. * Returns the Submesh.
  34297. */
  34298. SubMesh.prototype.updateBoundingInfo = function (world) {
  34299. var boundingInfo = this.getBoundingInfo();
  34300. if (!boundingInfo) {
  34301. this.refreshBoundingInfo();
  34302. boundingInfo = this.getBoundingInfo();
  34303. }
  34304. boundingInfo.update(world);
  34305. return this;
  34306. };
  34307. /**
  34308. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34309. * Boolean returned.
  34310. */
  34311. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34312. var boundingInfo = this.getBoundingInfo();
  34313. if (!boundingInfo) {
  34314. return false;
  34315. }
  34316. return boundingInfo.isInFrustum(frustumPlanes);
  34317. };
  34318. /**
  34319. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34320. * Boolean returned.
  34321. */
  34322. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34323. var boundingInfo = this.getBoundingInfo();
  34324. if (!boundingInfo) {
  34325. return false;
  34326. }
  34327. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34328. };
  34329. /**
  34330. * Renders the submesh.
  34331. * Returns it.
  34332. */
  34333. SubMesh.prototype.render = function (enableAlphaMode) {
  34334. this._renderingMesh.render(this, enableAlphaMode);
  34335. return this;
  34336. };
  34337. /**
  34338. * Returns a new Index Buffer.
  34339. * Type returned : WebGLBuffer.
  34340. */
  34341. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34342. if (!this._linesIndexBuffer) {
  34343. var linesIndices = [];
  34344. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34345. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34346. }
  34347. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34348. this.linesIndexCount = linesIndices.length;
  34349. }
  34350. return this._linesIndexBuffer;
  34351. };
  34352. /**
  34353. * True is the passed Ray intersects the submesh bounding box.
  34354. * Boolean returned.
  34355. */
  34356. SubMesh.prototype.canIntersects = function (ray) {
  34357. var boundingInfo = this.getBoundingInfo();
  34358. if (!boundingInfo) {
  34359. return false;
  34360. }
  34361. return ray.intersectsBox(boundingInfo.boundingBox);
  34362. };
  34363. /**
  34364. * Returns an object IntersectionInfo.
  34365. */
  34366. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34367. var intersectInfo = null;
  34368. var material = this.getMaterial();
  34369. if (!material) {
  34370. return null;
  34371. }
  34372. switch (material.fillMode) {
  34373. case BABYLON.Material.PointListDrawMode:
  34374. case BABYLON.Material.LineListDrawMode:
  34375. case BABYLON.Material.LineLoopDrawMode:
  34376. case BABYLON.Material.LineStripDrawMode:
  34377. case BABYLON.Material.TriangleFanDrawMode:
  34378. case BABYLON.Material.TriangleStripDrawMode:
  34379. return null;
  34380. }
  34381. // LineMesh first as it's also a Mesh...
  34382. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34383. var lineMesh = this._mesh;
  34384. // Line test
  34385. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34386. var p0 = positions[indices[index]];
  34387. var p1 = positions[indices[index + 1]];
  34388. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34389. if (length < 0) {
  34390. continue;
  34391. }
  34392. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34393. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34394. if (fastCheck) {
  34395. break;
  34396. }
  34397. }
  34398. }
  34399. }
  34400. else {
  34401. // Triangles test
  34402. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34403. var p0 = positions[indices[index]];
  34404. var p1 = positions[indices[index + 1]];
  34405. var p2 = positions[indices[index + 2]];
  34406. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34407. if (currentIntersectInfo) {
  34408. if (currentIntersectInfo.distance < 0) {
  34409. continue;
  34410. }
  34411. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34412. intersectInfo = currentIntersectInfo;
  34413. intersectInfo.faceId = index / 3;
  34414. if (fastCheck) {
  34415. break;
  34416. }
  34417. }
  34418. }
  34419. }
  34420. }
  34421. return intersectInfo;
  34422. };
  34423. /** @hidden */
  34424. SubMesh.prototype._rebuild = function () {
  34425. if (this._linesIndexBuffer) {
  34426. this._linesIndexBuffer = null;
  34427. }
  34428. };
  34429. // Clone
  34430. /**
  34431. * Creates a new Submesh from the passed Mesh.
  34432. */
  34433. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34434. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34435. if (!this.IsGlobal) {
  34436. var boundingInfo = this.getBoundingInfo();
  34437. if (!boundingInfo) {
  34438. return result;
  34439. }
  34440. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34441. }
  34442. return result;
  34443. };
  34444. // Dispose
  34445. /**
  34446. * Disposes the Submesh.
  34447. * Returns nothing.
  34448. */
  34449. SubMesh.prototype.dispose = function () {
  34450. if (this._linesIndexBuffer) {
  34451. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34452. this._linesIndexBuffer = null;
  34453. }
  34454. // Remove from mesh
  34455. var index = this._mesh.subMeshes.indexOf(this);
  34456. this._mesh.subMeshes.splice(index, 1);
  34457. };
  34458. // Statics
  34459. /**
  34460. * Creates a new Submesh from the passed parameters :
  34461. * - materialIndex (integer) : the index of the main mesh material.
  34462. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34463. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34464. * - mesh (Mesh) : the main mesh to create the submesh from.
  34465. * - renderingMesh (optional Mesh) : rendering mesh.
  34466. */
  34467. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34468. var minVertexIndex = Number.MAX_VALUE;
  34469. var maxVertexIndex = -Number.MAX_VALUE;
  34470. renderingMesh = (renderingMesh || mesh);
  34471. var indices = renderingMesh.getIndices();
  34472. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34473. var vertexIndex = indices[index];
  34474. if (vertexIndex < minVertexIndex)
  34475. minVertexIndex = vertexIndex;
  34476. if (vertexIndex > maxVertexIndex)
  34477. maxVertexIndex = vertexIndex;
  34478. }
  34479. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34480. };
  34481. return SubMesh;
  34482. }(BaseSubMesh));
  34483. BABYLON.SubMesh = SubMesh;
  34484. })(BABYLON || (BABYLON = {}));
  34485. //# sourceMappingURL=babylon.subMesh.js.map
  34486. var __assign = (this && this.__assign) || function () {
  34487. __assign = Object.assign || function(t) {
  34488. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34489. s = arguments[i];
  34490. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34491. t[p] = s[p];
  34492. }
  34493. return t;
  34494. };
  34495. return __assign.apply(this, arguments);
  34496. };
  34497. var BABYLON;
  34498. (function (BABYLON) {
  34499. /**
  34500. * Manages the defines for the Material
  34501. */
  34502. var MaterialDefines = /** @class */ (function () {
  34503. function MaterialDefines() {
  34504. this._isDirty = true;
  34505. /** @hidden */
  34506. this._areLightsDirty = true;
  34507. /** @hidden */
  34508. this._areAttributesDirty = true;
  34509. /** @hidden */
  34510. this._areTexturesDirty = true;
  34511. /** @hidden */
  34512. this._areFresnelDirty = true;
  34513. /** @hidden */
  34514. this._areMiscDirty = true;
  34515. /** @hidden */
  34516. this._areImageProcessingDirty = true;
  34517. /** @hidden */
  34518. this._normals = false;
  34519. /** @hidden */
  34520. this._uvs = false;
  34521. /** @hidden */
  34522. this._needNormals = false;
  34523. /** @hidden */
  34524. this._needUVs = false;
  34525. }
  34526. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34527. /**
  34528. * Specifies if the material needs to be re-calculated
  34529. */
  34530. get: function () {
  34531. return this._isDirty;
  34532. },
  34533. enumerable: true,
  34534. configurable: true
  34535. });
  34536. /**
  34537. * Marks the material to indicate that it has been re-calculated
  34538. */
  34539. MaterialDefines.prototype.markAsProcessed = function () {
  34540. this._isDirty = false;
  34541. this._areAttributesDirty = false;
  34542. this._areTexturesDirty = false;
  34543. this._areFresnelDirty = false;
  34544. this._areLightsDirty = false;
  34545. this._areMiscDirty = false;
  34546. this._areImageProcessingDirty = false;
  34547. };
  34548. /**
  34549. * Marks the material to indicate that it needs to be re-calculated
  34550. */
  34551. MaterialDefines.prototype.markAsUnprocessed = function () {
  34552. this._isDirty = true;
  34553. };
  34554. /**
  34555. * Marks the material to indicate all of its defines need to be re-calculated
  34556. */
  34557. MaterialDefines.prototype.markAllAsDirty = function () {
  34558. this._areTexturesDirty = true;
  34559. this._areAttributesDirty = true;
  34560. this._areLightsDirty = true;
  34561. this._areFresnelDirty = true;
  34562. this._areMiscDirty = true;
  34563. this._areImageProcessingDirty = true;
  34564. this._isDirty = true;
  34565. };
  34566. /**
  34567. * Marks the material to indicate that image processing needs to be re-calculated
  34568. */
  34569. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34570. this._areImageProcessingDirty = true;
  34571. this._isDirty = true;
  34572. };
  34573. /**
  34574. * Marks the material to indicate the lights need to be re-calculated
  34575. */
  34576. MaterialDefines.prototype.markAsLightDirty = function () {
  34577. this._areLightsDirty = true;
  34578. this._isDirty = true;
  34579. };
  34580. /**
  34581. * Marks the attribute state as changed
  34582. */
  34583. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34584. this._areAttributesDirty = true;
  34585. this._isDirty = true;
  34586. };
  34587. /**
  34588. * Marks the texture state as changed
  34589. */
  34590. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34591. this._areTexturesDirty = true;
  34592. this._isDirty = true;
  34593. };
  34594. /**
  34595. * Marks the fresnel state as changed
  34596. */
  34597. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34598. this._areFresnelDirty = true;
  34599. this._isDirty = true;
  34600. };
  34601. /**
  34602. * Marks the misc state as changed
  34603. */
  34604. MaterialDefines.prototype.markAsMiscDirty = function () {
  34605. this._areMiscDirty = true;
  34606. this._isDirty = true;
  34607. };
  34608. /**
  34609. * Rebuilds the material defines
  34610. */
  34611. MaterialDefines.prototype.rebuild = function () {
  34612. if (this._keys) {
  34613. delete this._keys;
  34614. }
  34615. this._keys = [];
  34616. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34617. var key = _a[_i];
  34618. if (key[0] === "_") {
  34619. continue;
  34620. }
  34621. this._keys.push(key);
  34622. }
  34623. };
  34624. /**
  34625. * Specifies if two material defines are equal
  34626. * @param other - A material define instance to compare to
  34627. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34628. */
  34629. MaterialDefines.prototype.isEqual = function (other) {
  34630. if (this._keys.length !== other._keys.length) {
  34631. return false;
  34632. }
  34633. for (var index = 0; index < this._keys.length; index++) {
  34634. var prop = this._keys[index];
  34635. if (this[prop] !== other[prop]) {
  34636. return false;
  34637. }
  34638. }
  34639. return true;
  34640. };
  34641. /**
  34642. * Clones this instance's defines to another instance
  34643. * @param other - material defines to clone values to
  34644. */
  34645. MaterialDefines.prototype.cloneTo = function (other) {
  34646. if (this._keys.length !== other._keys.length) {
  34647. other._keys = this._keys.slice(0);
  34648. }
  34649. for (var index = 0; index < this._keys.length; index++) {
  34650. var prop = this._keys[index];
  34651. other[prop] = this[prop];
  34652. }
  34653. };
  34654. /**
  34655. * Resets the material define values
  34656. */
  34657. MaterialDefines.prototype.reset = function () {
  34658. for (var index = 0; index < this._keys.length; index++) {
  34659. var prop = this._keys[index];
  34660. var type = typeof this[prop];
  34661. switch (type) {
  34662. case "number":
  34663. this[prop] = 0;
  34664. break;
  34665. case "string":
  34666. this[prop] = "";
  34667. break;
  34668. default:
  34669. this[prop] = false;
  34670. break;
  34671. }
  34672. }
  34673. };
  34674. /**
  34675. * Converts the material define values to a string
  34676. * @returns - String of material define information
  34677. */
  34678. MaterialDefines.prototype.toString = function () {
  34679. var result = "";
  34680. for (var index = 0; index < this._keys.length; index++) {
  34681. var prop = this._keys[index];
  34682. var value = this[prop];
  34683. var type = typeof value;
  34684. switch (type) {
  34685. case "number":
  34686. case "string":
  34687. result += "#define " + prop + " " + value + "\n";
  34688. break;
  34689. default:
  34690. if (value) {
  34691. result += "#define " + prop + "\n";
  34692. }
  34693. break;
  34694. }
  34695. }
  34696. return result;
  34697. };
  34698. return MaterialDefines;
  34699. }());
  34700. BABYLON.MaterialDefines = MaterialDefines;
  34701. /**
  34702. * Base class for the main features of a material in Babylon.js
  34703. */
  34704. var Material = /** @class */ (function () {
  34705. /**
  34706. * Creates a material instance
  34707. * @param name defines the name of the material
  34708. * @param scene defines the scene to reference
  34709. * @param doNotAdd specifies if the material should be added to the scene
  34710. */
  34711. function Material(name, scene, doNotAdd) {
  34712. /**
  34713. * Specifies if the ready state should be checked on each call
  34714. */
  34715. this.checkReadyOnEveryCall = false;
  34716. /**
  34717. * Specifies if the ready state should be checked once
  34718. */
  34719. this.checkReadyOnlyOnce = false;
  34720. /**
  34721. * The state of the material
  34722. */
  34723. this.state = "";
  34724. /**
  34725. * The alpha value of the material
  34726. */
  34727. this._alpha = 1.0;
  34728. /**
  34729. * Specifies if back face culling is enabled
  34730. */
  34731. this._backFaceCulling = true;
  34732. /**
  34733. * Specifies if the material should be serialized
  34734. */
  34735. this.doNotSerialize = false;
  34736. /**
  34737. * Specifies if the effect should be stored on sub meshes
  34738. */
  34739. this.storeEffectOnSubMeshes = false;
  34740. /**
  34741. * An event triggered when the material is disposed
  34742. */
  34743. this.onDisposeObservable = new BABYLON.Observable();
  34744. /**
  34745. * Stores the value of the alpha mode
  34746. */
  34747. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34748. /**
  34749. * Stores the state of the need depth pre-pass value
  34750. */
  34751. this._needDepthPrePass = false;
  34752. /**
  34753. * Specifies if depth writing should be disabled
  34754. */
  34755. this.disableDepthWrite = false;
  34756. /**
  34757. * Specifies if depth writing should be forced
  34758. */
  34759. this.forceDepthWrite = false;
  34760. /**
  34761. * Specifies if there should be a separate pass for culling
  34762. */
  34763. this.separateCullingPass = false;
  34764. /**
  34765. * Stores the state specifing if fog should be enabled
  34766. */
  34767. this._fogEnabled = true;
  34768. /**
  34769. * Stores the size of points
  34770. */
  34771. this.pointSize = 1.0;
  34772. /**
  34773. * Stores the z offset value
  34774. */
  34775. this.zOffset = 0;
  34776. /**
  34777. * @hidden
  34778. * Specifies if the material was previously ready
  34779. */
  34780. this._wasPreviouslyReady = false;
  34781. /**
  34782. * Stores the fill mode state
  34783. */
  34784. this._fillMode = Material.TriangleFillMode;
  34785. this.name = name;
  34786. this.id = name || BABYLON.Tools.RandomId();
  34787. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34788. this.uniqueId = this._scene.getUniqueId();
  34789. if (this._scene.useRightHandedSystem) {
  34790. this.sideOrientation = Material.ClockWiseSideOrientation;
  34791. }
  34792. else {
  34793. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34794. }
  34795. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34796. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34797. if (!doNotAdd) {
  34798. this._scene.materials.push(this);
  34799. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  34800. }
  34801. }
  34802. Object.defineProperty(Material, "TriangleFillMode", {
  34803. /**
  34804. * Returns the triangle fill mode
  34805. */
  34806. get: function () {
  34807. return Material._TriangleFillMode;
  34808. },
  34809. enumerable: true,
  34810. configurable: true
  34811. });
  34812. Object.defineProperty(Material, "WireFrameFillMode", {
  34813. /**
  34814. * Returns the wireframe mode
  34815. */
  34816. get: function () {
  34817. return Material._WireFrameFillMode;
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(Material, "PointFillMode", {
  34823. /**
  34824. * Returns the point fill mode
  34825. */
  34826. get: function () {
  34827. return Material._PointFillMode;
  34828. },
  34829. enumerable: true,
  34830. configurable: true
  34831. });
  34832. Object.defineProperty(Material, "PointListDrawMode", {
  34833. /**
  34834. * Returns the point list draw mode
  34835. */
  34836. get: function () {
  34837. return Material._PointListDrawMode;
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. Object.defineProperty(Material, "LineListDrawMode", {
  34843. /**
  34844. * Returns the line list draw mode
  34845. */
  34846. get: function () {
  34847. return Material._LineListDrawMode;
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. Object.defineProperty(Material, "LineLoopDrawMode", {
  34853. /**
  34854. * Returns the line loop draw mode
  34855. */
  34856. get: function () {
  34857. return Material._LineLoopDrawMode;
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(Material, "LineStripDrawMode", {
  34863. /**
  34864. * Returns the line strip draw mode
  34865. */
  34866. get: function () {
  34867. return Material._LineStripDrawMode;
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34873. /**
  34874. * Returns the triangle strip draw mode
  34875. */
  34876. get: function () {
  34877. return Material._TriangleStripDrawMode;
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34883. /**
  34884. * Returns the triangle fan draw mode
  34885. */
  34886. get: function () {
  34887. return Material._TriangleFanDrawMode;
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34893. /**
  34894. * Returns the clock-wise side orientation
  34895. */
  34896. get: function () {
  34897. return Material._ClockWiseSideOrientation;
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34903. /**
  34904. * Returns the counter clock-wise side orientation
  34905. */
  34906. get: function () {
  34907. return Material._CounterClockWiseSideOrientation;
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. Object.defineProperty(Material.prototype, "alpha", {
  34913. /**
  34914. * Gets the alpha value of the material
  34915. */
  34916. get: function () {
  34917. return this._alpha;
  34918. },
  34919. /**
  34920. * Sets the alpha value of the material
  34921. */
  34922. set: function (value) {
  34923. if (this._alpha === value) {
  34924. return;
  34925. }
  34926. this._alpha = value;
  34927. this.markAsDirty(Material.MiscDirtyFlag);
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34933. /**
  34934. * Gets the back-face culling state
  34935. */
  34936. get: function () {
  34937. return this._backFaceCulling;
  34938. },
  34939. /**
  34940. * Sets the back-face culling state
  34941. */
  34942. set: function (value) {
  34943. if (this._backFaceCulling === value) {
  34944. return;
  34945. }
  34946. this._backFaceCulling = value;
  34947. this.markAsDirty(Material.TextureDirtyFlag);
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  34953. /**
  34954. * Gets a boolean indicating that current material needs to register RTT
  34955. */
  34956. get: function () {
  34957. return false;
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. Object.defineProperty(Material.prototype, "onDispose", {
  34963. /**
  34964. * Called during a dispose event
  34965. */
  34966. set: function (callback) {
  34967. if (this._onDisposeObserver) {
  34968. this.onDisposeObservable.remove(this._onDisposeObserver);
  34969. }
  34970. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(Material.prototype, "onBindObservable", {
  34976. /**
  34977. * An event triggered when the material is bound
  34978. */
  34979. get: function () {
  34980. if (!this._onBindObservable) {
  34981. this._onBindObservable = new BABYLON.Observable();
  34982. }
  34983. return this._onBindObservable;
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(Material.prototype, "onBind", {
  34989. /**
  34990. * Called during a bind event
  34991. */
  34992. set: function (callback) {
  34993. if (this._onBindObserver) {
  34994. this.onBindObservable.remove(this._onBindObserver);
  34995. }
  34996. this._onBindObserver = this.onBindObservable.add(callback);
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35002. /**
  35003. * An event triggered when the material is unbound
  35004. */
  35005. get: function () {
  35006. if (!this._onUnBindObservable) {
  35007. this._onUnBindObservable = new BABYLON.Observable();
  35008. }
  35009. return this._onUnBindObservable;
  35010. },
  35011. enumerable: true,
  35012. configurable: true
  35013. });
  35014. Object.defineProperty(Material.prototype, "alphaMode", {
  35015. /**
  35016. * Gets the value of the alpha mode
  35017. */
  35018. get: function () {
  35019. return this._alphaMode;
  35020. },
  35021. /**
  35022. * Sets the value of the alpha mode.
  35023. *
  35024. * | Value | Type | Description |
  35025. * | --- | --- | --- |
  35026. * | 0 | ALPHA_DISABLE | |
  35027. * | 1 | ALPHA_ADD | |
  35028. * | 2 | ALPHA_COMBINE | |
  35029. * | 3 | ALPHA_SUBTRACT | |
  35030. * | 4 | ALPHA_MULTIPLY | |
  35031. * | 5 | ALPHA_MAXIMIZED | |
  35032. * | 6 | ALPHA_ONEONE | |
  35033. * | 7 | ALPHA_PREMULTIPLIED | |
  35034. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35035. * | 9 | ALPHA_INTERPOLATE | |
  35036. * | 10 | ALPHA_SCREENMODE | |
  35037. *
  35038. */
  35039. set: function (value) {
  35040. if (this._alphaMode === value) {
  35041. return;
  35042. }
  35043. this._alphaMode = value;
  35044. this.markAsDirty(Material.TextureDirtyFlag);
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35050. /**
  35051. * Gets the depth pre-pass value
  35052. */
  35053. get: function () {
  35054. return this._needDepthPrePass;
  35055. },
  35056. /**
  35057. * Sets the need depth pre-pass value
  35058. */
  35059. set: function (value) {
  35060. if (this._needDepthPrePass === value) {
  35061. return;
  35062. }
  35063. this._needDepthPrePass = value;
  35064. if (this._needDepthPrePass) {
  35065. this.checkReadyOnEveryCall = true;
  35066. }
  35067. },
  35068. enumerable: true,
  35069. configurable: true
  35070. });
  35071. Object.defineProperty(Material.prototype, "fogEnabled", {
  35072. /**
  35073. * Gets the value of the fog enabled state
  35074. */
  35075. get: function () {
  35076. return this._fogEnabled;
  35077. },
  35078. /**
  35079. * Sets the state for enabling fog
  35080. */
  35081. set: function (value) {
  35082. if (this._fogEnabled === value) {
  35083. return;
  35084. }
  35085. this._fogEnabled = value;
  35086. this.markAsDirty(Material.MiscDirtyFlag);
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(Material.prototype, "wireframe", {
  35092. /**
  35093. * Gets a value specifying if wireframe mode is enabled
  35094. */
  35095. get: function () {
  35096. switch (this._fillMode) {
  35097. case Material.WireFrameFillMode:
  35098. case Material.LineListDrawMode:
  35099. case Material.LineLoopDrawMode:
  35100. case Material.LineStripDrawMode:
  35101. return true;
  35102. }
  35103. return this._scene.forceWireframe;
  35104. },
  35105. /**
  35106. * Sets the state of wireframe mode
  35107. */
  35108. set: function (value) {
  35109. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35110. },
  35111. enumerable: true,
  35112. configurable: true
  35113. });
  35114. Object.defineProperty(Material.prototype, "pointsCloud", {
  35115. /**
  35116. * Gets the value specifying if point clouds are enabled
  35117. */
  35118. get: function () {
  35119. switch (this._fillMode) {
  35120. case Material.PointFillMode:
  35121. case Material.PointListDrawMode:
  35122. return true;
  35123. }
  35124. return this._scene.forcePointsCloud;
  35125. },
  35126. /**
  35127. * Sets the state of point cloud mode
  35128. */
  35129. set: function (value) {
  35130. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Material.prototype, "fillMode", {
  35136. /**
  35137. * Gets the material fill mode
  35138. */
  35139. get: function () {
  35140. return this._fillMode;
  35141. },
  35142. /**
  35143. * Sets the material fill mode
  35144. */
  35145. set: function (value) {
  35146. if (this._fillMode === value) {
  35147. return;
  35148. }
  35149. this._fillMode = value;
  35150. this.markAsDirty(Material.MiscDirtyFlag);
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. /**
  35156. * Returns a string representation of the current material
  35157. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35158. * @returns a string with material information
  35159. */
  35160. Material.prototype.toString = function (fullDetails) {
  35161. var ret = "Name: " + this.name;
  35162. if (fullDetails) {
  35163. }
  35164. return ret;
  35165. };
  35166. /**
  35167. * Gets the class name of the material
  35168. * @returns a string with the class name of the material
  35169. */
  35170. Material.prototype.getClassName = function () {
  35171. return "Material";
  35172. };
  35173. Object.defineProperty(Material.prototype, "isFrozen", {
  35174. /**
  35175. * Specifies if updates for the material been locked
  35176. */
  35177. get: function () {
  35178. return this.checkReadyOnlyOnce;
  35179. },
  35180. enumerable: true,
  35181. configurable: true
  35182. });
  35183. /**
  35184. * Locks updates for the material
  35185. */
  35186. Material.prototype.freeze = function () {
  35187. this.checkReadyOnlyOnce = true;
  35188. };
  35189. /**
  35190. * Unlocks updates for the material
  35191. */
  35192. Material.prototype.unfreeze = function () {
  35193. this.checkReadyOnlyOnce = false;
  35194. };
  35195. /**
  35196. * Specifies if the material is ready to be used
  35197. * @param mesh defines the mesh to check
  35198. * @param useInstances specifies if instances should be used
  35199. * @returns a boolean indicating if the material is ready to be used
  35200. */
  35201. Material.prototype.isReady = function (mesh, useInstances) {
  35202. return true;
  35203. };
  35204. /**
  35205. * Specifies that the submesh is ready to be used
  35206. * @param mesh defines the mesh to check
  35207. * @param subMesh defines which submesh to check
  35208. * @param useInstances specifies that instances should be used
  35209. * @returns a boolean indicating that the submesh is ready or not
  35210. */
  35211. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35212. return false;
  35213. };
  35214. /**
  35215. * Returns the material effect
  35216. * @returns the effect associated with the material
  35217. */
  35218. Material.prototype.getEffect = function () {
  35219. return this._effect;
  35220. };
  35221. /**
  35222. * Returns the current scene
  35223. * @returns a Scene
  35224. */
  35225. Material.prototype.getScene = function () {
  35226. return this._scene;
  35227. };
  35228. /**
  35229. * Specifies if the material will require alpha blending
  35230. * @returns a boolean specifying if alpha blending is needed
  35231. */
  35232. Material.prototype.needAlphaBlending = function () {
  35233. return (this.alpha < 1.0);
  35234. };
  35235. /**
  35236. * Specifies if the mesh will require alpha blending
  35237. * @param mesh defines the mesh to check
  35238. * @returns a boolean specifying if alpha blending is needed for the mesh
  35239. */
  35240. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35241. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35242. };
  35243. /**
  35244. * Specifies if this material should be rendered in alpha test mode
  35245. * @returns a boolean specifying if an alpha test is needed.
  35246. */
  35247. Material.prototype.needAlphaTesting = function () {
  35248. return false;
  35249. };
  35250. /**
  35251. * Gets the texture used for the alpha test
  35252. * @returns the texture to use for alpha testing
  35253. */
  35254. Material.prototype.getAlphaTestTexture = function () {
  35255. return null;
  35256. };
  35257. /**
  35258. * Marks the material to indicate that it needs to be re-calculated
  35259. */
  35260. Material.prototype.markDirty = function () {
  35261. this._wasPreviouslyReady = false;
  35262. };
  35263. /** @hidden */
  35264. Material.prototype._preBind = function (effect, overrideOrientation) {
  35265. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35266. var engine = this._scene.getEngine();
  35267. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35268. var reverse = orientation === Material.ClockWiseSideOrientation;
  35269. engine.enableEffect(effect ? effect : this._effect);
  35270. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35271. return reverse;
  35272. };
  35273. /**
  35274. * Binds the material to the mesh
  35275. * @param world defines the world transformation matrix
  35276. * @param mesh defines the mesh to bind the material to
  35277. */
  35278. Material.prototype.bind = function (world, mesh) {
  35279. };
  35280. /**
  35281. * Binds the submesh to the material
  35282. * @param world defines the world transformation matrix
  35283. * @param mesh defines the mesh containing the submesh
  35284. * @param subMesh defines the submesh to bind the material to
  35285. */
  35286. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35287. };
  35288. /**
  35289. * Binds the world matrix to the material
  35290. * @param world defines the world transformation matrix
  35291. */
  35292. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35293. };
  35294. /**
  35295. * Binds the scene's uniform buffer to the effect.
  35296. * @param effect defines the effect to bind to the scene uniform buffer
  35297. * @param sceneUbo defines the uniform buffer storing scene data
  35298. */
  35299. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35300. sceneUbo.bindToEffect(effect, "Scene");
  35301. };
  35302. /**
  35303. * Binds the view matrix to the effect
  35304. * @param effect defines the effect to bind the view matrix to
  35305. */
  35306. Material.prototype.bindView = function (effect) {
  35307. if (!this._useUBO) {
  35308. effect.setMatrix("view", this.getScene().getViewMatrix());
  35309. }
  35310. else {
  35311. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35312. }
  35313. };
  35314. /**
  35315. * Binds the view projection matrix to the effect
  35316. * @param effect defines the effect to bind the view projection matrix to
  35317. */
  35318. Material.prototype.bindViewProjection = function (effect) {
  35319. if (!this._useUBO) {
  35320. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35321. }
  35322. else {
  35323. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35324. }
  35325. };
  35326. /**
  35327. * Specifies if material alpha testing should be turned on for the mesh
  35328. * @param mesh defines the mesh to check
  35329. */
  35330. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35331. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35332. };
  35333. /**
  35334. * Processes to execute after binding the material to a mesh
  35335. * @param mesh defines the rendered mesh
  35336. */
  35337. Material.prototype._afterBind = function (mesh) {
  35338. this._scene._cachedMaterial = this;
  35339. if (mesh) {
  35340. this._scene._cachedVisibility = mesh.visibility;
  35341. }
  35342. else {
  35343. this._scene._cachedVisibility = 1;
  35344. }
  35345. if (this._onBindObservable && mesh) {
  35346. this._onBindObservable.notifyObservers(mesh);
  35347. }
  35348. if (this.disableDepthWrite) {
  35349. var engine = this._scene.getEngine();
  35350. this._cachedDepthWriteState = engine.getDepthWrite();
  35351. engine.setDepthWrite(false);
  35352. }
  35353. };
  35354. /**
  35355. * Unbinds the material from the mesh
  35356. */
  35357. Material.prototype.unbind = function () {
  35358. if (this._onUnBindObservable) {
  35359. this._onUnBindObservable.notifyObservers(this);
  35360. }
  35361. if (this.disableDepthWrite) {
  35362. var engine = this._scene.getEngine();
  35363. engine.setDepthWrite(this._cachedDepthWriteState);
  35364. }
  35365. };
  35366. /**
  35367. * Gets the active textures from the material
  35368. * @returns an array of textures
  35369. */
  35370. Material.prototype.getActiveTextures = function () {
  35371. return [];
  35372. };
  35373. /**
  35374. * Specifies if the material uses a texture
  35375. * @param texture defines the texture to check against the material
  35376. * @returns a boolean specifying if the material uses the texture
  35377. */
  35378. Material.prototype.hasTexture = function (texture) {
  35379. return false;
  35380. };
  35381. /**
  35382. * Makes a duplicate of the material, and gives it a new name
  35383. * @param name defines the new name for the duplicated material
  35384. * @returns the cloned material
  35385. */
  35386. Material.prototype.clone = function (name) {
  35387. return null;
  35388. };
  35389. /**
  35390. * Gets the meshes bound to the material
  35391. * @returns an array of meshes bound to the material
  35392. */
  35393. Material.prototype.getBindedMeshes = function () {
  35394. var result = new Array();
  35395. for (var index = 0; index < this._scene.meshes.length; index++) {
  35396. var mesh = this._scene.meshes[index];
  35397. if (mesh.material === this) {
  35398. result.push(mesh);
  35399. }
  35400. }
  35401. return result;
  35402. };
  35403. /**
  35404. * Force shader compilation
  35405. * @param mesh defines the mesh associated with this material
  35406. * @param onCompiled defines a function to execute once the material is compiled
  35407. * @param options defines the options to configure the compilation
  35408. */
  35409. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35410. var _this = this;
  35411. var localOptions = __assign({ clipPlane: false }, options);
  35412. var subMesh = new BABYLON.BaseSubMesh();
  35413. var scene = this.getScene();
  35414. var checkReady = function () {
  35415. if (!_this._scene || !_this._scene.getEngine()) {
  35416. return;
  35417. }
  35418. if (subMesh._materialDefines) {
  35419. subMesh._materialDefines._renderId = -1;
  35420. }
  35421. var clipPlaneState = scene.clipPlane;
  35422. if (localOptions.clipPlane) {
  35423. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35424. }
  35425. if (_this.storeEffectOnSubMeshes) {
  35426. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35427. if (onCompiled) {
  35428. onCompiled(_this);
  35429. }
  35430. }
  35431. else {
  35432. setTimeout(checkReady, 16);
  35433. }
  35434. }
  35435. else {
  35436. if (_this.isReady(mesh)) {
  35437. if (onCompiled) {
  35438. onCompiled(_this);
  35439. }
  35440. }
  35441. else {
  35442. setTimeout(checkReady, 16);
  35443. }
  35444. }
  35445. if (localOptions.clipPlane) {
  35446. scene.clipPlane = clipPlaneState;
  35447. }
  35448. };
  35449. checkReady();
  35450. };
  35451. /**
  35452. * Force shader compilation
  35453. * @param mesh defines the mesh that will use this material
  35454. * @param options defines additional options for compiling the shaders
  35455. * @returns a promise that resolves when the compilation completes
  35456. */
  35457. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35458. var _this = this;
  35459. return new Promise(function (resolve) {
  35460. _this.forceCompilation(mesh, function () {
  35461. resolve();
  35462. }, options);
  35463. });
  35464. };
  35465. /**
  35466. * Marks a define in the material to indicate that it needs to be re-computed
  35467. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35468. */
  35469. Material.prototype.markAsDirty = function (flag) {
  35470. if (flag & Material.TextureDirtyFlag) {
  35471. this._markAllSubMeshesAsTexturesDirty();
  35472. }
  35473. if (flag & Material.LightDirtyFlag) {
  35474. this._markAllSubMeshesAsLightsDirty();
  35475. }
  35476. if (flag & Material.FresnelDirtyFlag) {
  35477. this._markAllSubMeshesAsFresnelDirty();
  35478. }
  35479. if (flag & Material.AttributesDirtyFlag) {
  35480. this._markAllSubMeshesAsAttributesDirty();
  35481. }
  35482. if (flag & Material.MiscDirtyFlag) {
  35483. this._markAllSubMeshesAsMiscDirty();
  35484. }
  35485. this.getScene().resetCachedMaterial();
  35486. };
  35487. /**
  35488. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35489. * @param func defines a function which checks material defines against the submeshes
  35490. */
  35491. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35492. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35493. var mesh = _a[_i];
  35494. if (!mesh.subMeshes) {
  35495. continue;
  35496. }
  35497. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35498. var subMesh = _c[_b];
  35499. if (subMesh.getMaterial() !== this) {
  35500. continue;
  35501. }
  35502. if (!subMesh._materialDefines) {
  35503. continue;
  35504. }
  35505. func(subMesh._materialDefines);
  35506. }
  35507. }
  35508. };
  35509. /**
  35510. * Indicates that image processing needs to be re-calculated for all submeshes
  35511. */
  35512. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35513. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35514. };
  35515. /**
  35516. * Indicates that textures need to be re-calculated for all submeshes
  35517. */
  35518. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35519. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35520. };
  35521. /**
  35522. * Indicates that fresnel needs to be re-calculated for all submeshes
  35523. */
  35524. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35525. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35526. };
  35527. /**
  35528. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35529. */
  35530. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35531. this._markAllSubMeshesAsDirty(function (defines) {
  35532. defines.markAsFresnelDirty();
  35533. defines.markAsMiscDirty();
  35534. });
  35535. };
  35536. /**
  35537. * Indicates that lights need to be re-calculated for all submeshes
  35538. */
  35539. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35540. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35541. };
  35542. /**
  35543. * Indicates that attributes need to be re-calculated for all submeshes
  35544. */
  35545. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35546. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35547. };
  35548. /**
  35549. * Indicates that misc needs to be re-calculated for all submeshes
  35550. */
  35551. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35552. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35553. };
  35554. /**
  35555. * Indicates that textures and misc need to be re-calculated for all submeshes
  35556. */
  35557. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35558. this._markAllSubMeshesAsDirty(function (defines) {
  35559. defines.markAsTexturesDirty();
  35560. defines.markAsMiscDirty();
  35561. });
  35562. };
  35563. /**
  35564. * Disposes the material
  35565. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35566. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35567. */
  35568. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35569. // Animations
  35570. this.getScene().stopAnimation(this);
  35571. this.getScene().freeProcessedMaterials();
  35572. // Remove from scene
  35573. var index = this._scene.materials.indexOf(this);
  35574. if (index >= 0) {
  35575. this._scene.materials.splice(index, 1);
  35576. }
  35577. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  35578. // Remove from meshes
  35579. for (index = 0; index < this._scene.meshes.length; index++) {
  35580. var mesh = this._scene.meshes[index];
  35581. if (mesh.material === this) {
  35582. mesh.material = null;
  35583. if (mesh.geometry) {
  35584. var geometry = (mesh.geometry);
  35585. if (this.storeEffectOnSubMeshes) {
  35586. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35587. var subMesh = _a[_i];
  35588. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35589. if (forceDisposeEffect && subMesh._materialEffect) {
  35590. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35591. }
  35592. }
  35593. }
  35594. else {
  35595. geometry._releaseVertexArrayObject(this._effect);
  35596. }
  35597. }
  35598. }
  35599. }
  35600. this._uniformBuffer.dispose();
  35601. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35602. if (forceDisposeEffect && this._effect) {
  35603. if (!this.storeEffectOnSubMeshes) {
  35604. this._scene.getEngine()._releaseEffect(this._effect);
  35605. }
  35606. this._effect = null;
  35607. }
  35608. // Callback
  35609. this.onDisposeObservable.notifyObservers(this);
  35610. this.onDisposeObservable.clear();
  35611. if (this._onBindObservable) {
  35612. this._onBindObservable.clear();
  35613. }
  35614. if (this._onUnBindObservable) {
  35615. this._onUnBindObservable.clear();
  35616. }
  35617. };
  35618. /**
  35619. * Serializes this material
  35620. * @returns the serialized material object
  35621. */
  35622. Material.prototype.serialize = function () {
  35623. return BABYLON.SerializationHelper.Serialize(this);
  35624. };
  35625. /**
  35626. * Creates a MultiMaterial from parsed MultiMaterial data.
  35627. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35628. * @param scene defines the hosting scene
  35629. * @returns a new MultiMaterial
  35630. */
  35631. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35632. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35633. multiMaterial.id = parsedMultiMaterial.id;
  35634. if (BABYLON.Tags) {
  35635. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35636. }
  35637. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35638. var subMatId = parsedMultiMaterial.materials[matIndex];
  35639. if (subMatId) {
  35640. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35641. }
  35642. else {
  35643. multiMaterial.subMaterials.push(null);
  35644. }
  35645. }
  35646. return multiMaterial;
  35647. };
  35648. /**
  35649. * Creates a material from parsed material data
  35650. * @param parsedMaterial defines parsed material data
  35651. * @param scene defines the hosting scene
  35652. * @param rootUrl defines the root URL to use to load textures
  35653. * @returns a new material
  35654. */
  35655. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35656. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35657. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35658. }
  35659. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35660. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35661. if (!BABYLON.LegacyPBRMaterial) {
  35662. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35663. return;
  35664. }
  35665. }
  35666. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35667. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35668. };
  35669. // Triangle views
  35670. Material._TriangleFillMode = 0;
  35671. Material._WireFrameFillMode = 1;
  35672. Material._PointFillMode = 2;
  35673. // Draw modes
  35674. Material._PointListDrawMode = 3;
  35675. Material._LineListDrawMode = 4;
  35676. Material._LineLoopDrawMode = 5;
  35677. Material._LineStripDrawMode = 6;
  35678. Material._TriangleStripDrawMode = 7;
  35679. Material._TriangleFanDrawMode = 8;
  35680. /**
  35681. * Stores the clock-wise side orientation
  35682. */
  35683. Material._ClockWiseSideOrientation = 0;
  35684. /**
  35685. * Stores the counter clock-wise side orientation
  35686. */
  35687. Material._CounterClockWiseSideOrientation = 1;
  35688. /**
  35689. * The dirty texture flag value
  35690. */
  35691. Material.TextureDirtyFlag = 1;
  35692. /**
  35693. * The dirty light flag value
  35694. */
  35695. Material.LightDirtyFlag = 2;
  35696. /**
  35697. * The dirty fresnel flag value
  35698. */
  35699. Material.FresnelDirtyFlag = 4;
  35700. /**
  35701. * The dirty attribute flag value
  35702. */
  35703. Material.AttributesDirtyFlag = 8;
  35704. /**
  35705. * The dirty misc flag value
  35706. */
  35707. Material.MiscDirtyFlag = 16;
  35708. /**
  35709. * The all dirty flag value
  35710. */
  35711. Material.AllDirtyFlag = 31;
  35712. __decorate([
  35713. BABYLON.serialize()
  35714. ], Material.prototype, "id", void 0);
  35715. __decorate([
  35716. BABYLON.serialize()
  35717. ], Material.prototype, "uniqueId", void 0);
  35718. __decorate([
  35719. BABYLON.serialize()
  35720. ], Material.prototype, "name", void 0);
  35721. __decorate([
  35722. BABYLON.serialize()
  35723. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35724. __decorate([
  35725. BABYLON.serialize()
  35726. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35727. __decorate([
  35728. BABYLON.serialize()
  35729. ], Material.prototype, "state", void 0);
  35730. __decorate([
  35731. BABYLON.serialize("alpha")
  35732. ], Material.prototype, "_alpha", void 0);
  35733. __decorate([
  35734. BABYLON.serialize("backFaceCulling")
  35735. ], Material.prototype, "_backFaceCulling", void 0);
  35736. __decorate([
  35737. BABYLON.serialize()
  35738. ], Material.prototype, "sideOrientation", void 0);
  35739. __decorate([
  35740. BABYLON.serialize("alphaMode")
  35741. ], Material.prototype, "_alphaMode", void 0);
  35742. __decorate([
  35743. BABYLON.serialize()
  35744. ], Material.prototype, "_needDepthPrePass", void 0);
  35745. __decorate([
  35746. BABYLON.serialize()
  35747. ], Material.prototype, "disableDepthWrite", void 0);
  35748. __decorate([
  35749. BABYLON.serialize()
  35750. ], Material.prototype, "forceDepthWrite", void 0);
  35751. __decorate([
  35752. BABYLON.serialize()
  35753. ], Material.prototype, "separateCullingPass", void 0);
  35754. __decorate([
  35755. BABYLON.serialize("fogEnabled")
  35756. ], Material.prototype, "_fogEnabled", void 0);
  35757. __decorate([
  35758. BABYLON.serialize()
  35759. ], Material.prototype, "pointSize", void 0);
  35760. __decorate([
  35761. BABYLON.serialize()
  35762. ], Material.prototype, "zOffset", void 0);
  35763. __decorate([
  35764. BABYLON.serialize()
  35765. ], Material.prototype, "wireframe", null);
  35766. __decorate([
  35767. BABYLON.serialize()
  35768. ], Material.prototype, "pointsCloud", null);
  35769. __decorate([
  35770. BABYLON.serialize()
  35771. ], Material.prototype, "fillMode", null);
  35772. return Material;
  35773. }());
  35774. BABYLON.Material = Material;
  35775. })(BABYLON || (BABYLON = {}));
  35776. //# sourceMappingURL=babylon.material.js.map
  35777. var BABYLON;
  35778. (function (BABYLON) {
  35779. var UniformBuffer = /** @class */ (function () {
  35780. /**
  35781. * Uniform buffer objects.
  35782. *
  35783. * Handles blocks of uniform on the GPU.
  35784. *
  35785. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35786. *
  35787. * For more information, please refer to :
  35788. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35789. */
  35790. function UniformBuffer(engine, data, dynamic) {
  35791. this._engine = engine;
  35792. this._noUBO = !engine.supportsUniformBuffers;
  35793. this._dynamic = dynamic;
  35794. this._data = data || [];
  35795. this._uniformLocations = {};
  35796. this._uniformSizes = {};
  35797. this._uniformLocationPointer = 0;
  35798. this._needSync = false;
  35799. if (this._noUBO) {
  35800. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35801. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35802. this.updateFloat = this._updateFloatForEffect;
  35803. this.updateFloat2 = this._updateFloat2ForEffect;
  35804. this.updateFloat3 = this._updateFloat3ForEffect;
  35805. this.updateFloat4 = this._updateFloat4ForEffect;
  35806. this.updateMatrix = this._updateMatrixForEffect;
  35807. this.updateVector3 = this._updateVector3ForEffect;
  35808. this.updateVector4 = this._updateVector4ForEffect;
  35809. this.updateColor3 = this._updateColor3ForEffect;
  35810. this.updateColor4 = this._updateColor4ForEffect;
  35811. }
  35812. else {
  35813. this._engine._uniformBuffers.push(this);
  35814. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35815. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35816. this.updateFloat = this._updateFloatForUniform;
  35817. this.updateFloat2 = this._updateFloat2ForUniform;
  35818. this.updateFloat3 = this._updateFloat3ForUniform;
  35819. this.updateFloat4 = this._updateFloat4ForUniform;
  35820. this.updateMatrix = this._updateMatrixForUniform;
  35821. this.updateVector3 = this._updateVector3ForUniform;
  35822. this.updateVector4 = this._updateVector4ForUniform;
  35823. this.updateColor3 = this._updateColor3ForUniform;
  35824. this.updateColor4 = this._updateColor4ForUniform;
  35825. }
  35826. }
  35827. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35828. // Properties
  35829. /**
  35830. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35831. * or just falling back on setUniformXXX calls.
  35832. */
  35833. get: function () {
  35834. return !this._noUBO;
  35835. },
  35836. enumerable: true,
  35837. configurable: true
  35838. });
  35839. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35840. /**
  35841. * Indicates if the WebGL underlying uniform buffer is in sync
  35842. * with the javascript cache data.
  35843. */
  35844. get: function () {
  35845. return !this._needSync;
  35846. },
  35847. enumerable: true,
  35848. configurable: true
  35849. });
  35850. /**
  35851. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35852. * Also, a dynamic UniformBuffer will disable cache verification and always
  35853. * update the underlying WebGL uniform buffer to the GPU.
  35854. */
  35855. UniformBuffer.prototype.isDynamic = function () {
  35856. return this._dynamic !== undefined;
  35857. };
  35858. /**
  35859. * The data cache on JS side.
  35860. */
  35861. UniformBuffer.prototype.getData = function () {
  35862. return this._bufferData;
  35863. };
  35864. /**
  35865. * The underlying WebGL Uniform buffer.
  35866. */
  35867. UniformBuffer.prototype.getBuffer = function () {
  35868. return this._buffer;
  35869. };
  35870. /**
  35871. * std140 layout specifies how to align data within an UBO structure.
  35872. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35873. * for specs.
  35874. */
  35875. UniformBuffer.prototype._fillAlignment = function (size) {
  35876. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35877. // and 4x4 matrices
  35878. // TODO : change if other types are used
  35879. var alignment;
  35880. if (size <= 2) {
  35881. alignment = size;
  35882. }
  35883. else {
  35884. alignment = 4;
  35885. }
  35886. if ((this._uniformLocationPointer % alignment) !== 0) {
  35887. var oldPointer = this._uniformLocationPointer;
  35888. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35889. var diff = this._uniformLocationPointer - oldPointer;
  35890. for (var i = 0; i < diff; i++) {
  35891. this._data.push(0);
  35892. }
  35893. }
  35894. };
  35895. /**
  35896. * Adds an uniform in the buffer.
  35897. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35898. * for the layout to be correct !
  35899. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35900. * @param {number|number[]} size Data size, or data directly.
  35901. */
  35902. UniformBuffer.prototype.addUniform = function (name, size) {
  35903. if (this._noUBO) {
  35904. return;
  35905. }
  35906. if (this._uniformLocations[name] !== undefined) {
  35907. // Already existing uniform
  35908. return;
  35909. }
  35910. // This function must be called in the order of the shader layout !
  35911. // size can be the size of the uniform, or data directly
  35912. var data;
  35913. if (size instanceof Array) {
  35914. data = size;
  35915. size = data.length;
  35916. }
  35917. else {
  35918. size = size;
  35919. data = [];
  35920. // Fill with zeros
  35921. for (var i = 0; i < size; i++) {
  35922. data.push(0);
  35923. }
  35924. }
  35925. this._fillAlignment(size);
  35926. this._uniformSizes[name] = size;
  35927. this._uniformLocations[name] = this._uniformLocationPointer;
  35928. this._uniformLocationPointer += size;
  35929. for (var i = 0; i < size; i++) {
  35930. this._data.push(data[i]);
  35931. }
  35932. this._needSync = true;
  35933. };
  35934. /**
  35935. * Wrapper for addUniform.
  35936. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35937. * @param {Matrix} mat A 4x4 matrix.
  35938. */
  35939. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35940. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35941. };
  35942. /**
  35943. * Wrapper for addUniform.
  35944. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35945. * @param {number} x
  35946. * @param {number} y
  35947. */
  35948. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35949. var temp = [x, y];
  35950. this.addUniform(name, temp);
  35951. };
  35952. /**
  35953. * Wrapper for addUniform.
  35954. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35955. * @param {number} x
  35956. * @param {number} y
  35957. * @param {number} z
  35958. */
  35959. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35960. var temp = [x, y, z];
  35961. this.addUniform(name, temp);
  35962. };
  35963. /**
  35964. * Wrapper for addUniform.
  35965. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35966. * @param {Color3} color
  35967. */
  35968. UniformBuffer.prototype.addColor3 = function (name, color) {
  35969. var temp = new Array();
  35970. color.toArray(temp);
  35971. this.addUniform(name, temp);
  35972. };
  35973. /**
  35974. * Wrapper for addUniform.
  35975. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35976. * @param {Color3} color
  35977. * @param {number} alpha
  35978. */
  35979. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35980. var temp = new Array();
  35981. color.toArray(temp);
  35982. temp.push(alpha);
  35983. this.addUniform(name, temp);
  35984. };
  35985. /**
  35986. * Wrapper for addUniform.
  35987. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35988. * @param {Vector3} vector
  35989. */
  35990. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35991. var temp = new Array();
  35992. vector.toArray(temp);
  35993. this.addUniform(name, temp);
  35994. };
  35995. /**
  35996. * Wrapper for addUniform.
  35997. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35998. */
  35999. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36000. this.addUniform(name, 12);
  36001. };
  36002. /**
  36003. * Wrapper for addUniform.
  36004. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36005. */
  36006. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36007. this.addUniform(name, 8);
  36008. };
  36009. /**
  36010. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36011. */
  36012. UniformBuffer.prototype.create = function () {
  36013. if (this._noUBO) {
  36014. return;
  36015. }
  36016. if (this._buffer) {
  36017. return; // nothing to do
  36018. }
  36019. // See spec, alignment must be filled as a vec4
  36020. this._fillAlignment(4);
  36021. this._bufferData = new Float32Array(this._data);
  36022. this._rebuild();
  36023. this._needSync = true;
  36024. };
  36025. /** @hidden */
  36026. UniformBuffer.prototype._rebuild = function () {
  36027. if (this._noUBO) {
  36028. return;
  36029. }
  36030. if (this._dynamic) {
  36031. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36032. }
  36033. else {
  36034. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36035. }
  36036. };
  36037. /**
  36038. * Updates the WebGL Uniform Buffer on the GPU.
  36039. * If the `dynamic` flag is set to true, no cache comparison is done.
  36040. * Otherwise, the buffer will be updated only if the cache differs.
  36041. */
  36042. UniformBuffer.prototype.update = function () {
  36043. if (!this._buffer) {
  36044. this.create();
  36045. return;
  36046. }
  36047. if (!this._dynamic && !this._needSync) {
  36048. return;
  36049. }
  36050. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36051. this._needSync = false;
  36052. };
  36053. /**
  36054. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36055. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36056. * @param {number[]|Float32Array} data Flattened data
  36057. * @param {number} size Size of the data.
  36058. */
  36059. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36060. var location = this._uniformLocations[uniformName];
  36061. if (location === undefined) {
  36062. if (this._buffer) {
  36063. // Cannot add an uniform if the buffer is already created
  36064. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36065. return;
  36066. }
  36067. this.addUniform(uniformName, size);
  36068. location = this._uniformLocations[uniformName];
  36069. }
  36070. if (!this._buffer) {
  36071. this.create();
  36072. }
  36073. if (!this._dynamic) {
  36074. // Cache for static uniform buffers
  36075. var changed = false;
  36076. for (var i = 0; i < size; i++) {
  36077. if (this._bufferData[location + i] !== data[i]) {
  36078. changed = true;
  36079. this._bufferData[location + i] = data[i];
  36080. }
  36081. }
  36082. this._needSync = this._needSync || changed;
  36083. }
  36084. else {
  36085. // No cache for dynamic
  36086. for (var i = 0; i < size; i++) {
  36087. this._bufferData[location + i] = data[i];
  36088. }
  36089. }
  36090. };
  36091. // Update methods
  36092. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36093. // To match std140, matrix must be realigned
  36094. for (var i = 0; i < 3; i++) {
  36095. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36096. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36097. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36098. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36099. }
  36100. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36101. };
  36102. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36103. this._currentEffect.setMatrix3x3(name, matrix);
  36104. };
  36105. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36106. this._currentEffect.setMatrix2x2(name, matrix);
  36107. };
  36108. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36109. // To match std140, matrix must be realigned
  36110. for (var i = 0; i < 2; i++) {
  36111. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36112. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36113. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36114. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36115. }
  36116. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36117. };
  36118. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36119. this._currentEffect.setFloat(name, x);
  36120. };
  36121. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36122. UniformBuffer._tempBuffer[0] = x;
  36123. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36124. };
  36125. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36126. if (suffix === void 0) { suffix = ""; }
  36127. this._currentEffect.setFloat2(name + suffix, x, y);
  36128. };
  36129. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36130. if (suffix === void 0) { suffix = ""; }
  36131. UniformBuffer._tempBuffer[0] = x;
  36132. UniformBuffer._tempBuffer[1] = y;
  36133. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36134. };
  36135. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36136. if (suffix === void 0) { suffix = ""; }
  36137. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36138. };
  36139. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36140. if (suffix === void 0) { suffix = ""; }
  36141. UniformBuffer._tempBuffer[0] = x;
  36142. UniformBuffer._tempBuffer[1] = y;
  36143. UniformBuffer._tempBuffer[2] = z;
  36144. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36145. };
  36146. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36147. if (suffix === void 0) { suffix = ""; }
  36148. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36149. };
  36150. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36151. if (suffix === void 0) { suffix = ""; }
  36152. UniformBuffer._tempBuffer[0] = x;
  36153. UniformBuffer._tempBuffer[1] = y;
  36154. UniformBuffer._tempBuffer[2] = z;
  36155. UniformBuffer._tempBuffer[3] = w;
  36156. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36157. };
  36158. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36159. this._currentEffect.setMatrix(name, mat);
  36160. };
  36161. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36162. this.updateUniform(name, mat.toArray(), 16);
  36163. };
  36164. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36165. this._currentEffect.setVector3(name, vector);
  36166. };
  36167. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36168. vector.toArray(UniformBuffer._tempBuffer);
  36169. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36170. };
  36171. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36172. this._currentEffect.setVector4(name, vector);
  36173. };
  36174. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36175. vector.toArray(UniformBuffer._tempBuffer);
  36176. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36177. };
  36178. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36179. if (suffix === void 0) { suffix = ""; }
  36180. this._currentEffect.setColor3(name + suffix, color);
  36181. };
  36182. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36183. if (suffix === void 0) { suffix = ""; }
  36184. color.toArray(UniformBuffer._tempBuffer);
  36185. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36186. };
  36187. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36188. if (suffix === void 0) { suffix = ""; }
  36189. this._currentEffect.setColor4(name + suffix, color, alpha);
  36190. };
  36191. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36192. if (suffix === void 0) { suffix = ""; }
  36193. color.toArray(UniformBuffer._tempBuffer);
  36194. UniformBuffer._tempBuffer[3] = alpha;
  36195. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36196. };
  36197. /**
  36198. * Sets a sampler uniform on the effect.
  36199. * @param {string} name Name of the sampler.
  36200. * @param {Texture} texture
  36201. */
  36202. UniformBuffer.prototype.setTexture = function (name, texture) {
  36203. this._currentEffect.setTexture(name, texture);
  36204. };
  36205. /**
  36206. * Directly updates the value of the uniform in the cache AND on the GPU.
  36207. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36208. * @param {number[]|Float32Array} data Flattened data
  36209. */
  36210. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36211. this.updateUniform(uniformName, data, data.length);
  36212. this.update();
  36213. };
  36214. /**
  36215. * Binds this uniform buffer to an effect.
  36216. * @param {Effect} effect
  36217. * @param {string} name Name of the uniform block in the shader.
  36218. */
  36219. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36220. this._currentEffect = effect;
  36221. if (this._noUBO || !this._buffer) {
  36222. return;
  36223. }
  36224. effect.bindUniformBuffer(this._buffer, name);
  36225. };
  36226. /**
  36227. * Disposes the uniform buffer.
  36228. */
  36229. UniformBuffer.prototype.dispose = function () {
  36230. if (this._noUBO) {
  36231. return;
  36232. }
  36233. var index = this._engine._uniformBuffers.indexOf(this);
  36234. if (index !== -1) {
  36235. this._engine._uniformBuffers.splice(index, 1);
  36236. }
  36237. if (!this._buffer) {
  36238. return;
  36239. }
  36240. if (this._engine._releaseBuffer(this._buffer)) {
  36241. this._buffer = null;
  36242. }
  36243. };
  36244. // Pool for avoiding memory leaks
  36245. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36246. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36247. return UniformBuffer;
  36248. }());
  36249. BABYLON.UniformBuffer = UniformBuffer;
  36250. })(BABYLON || (BABYLON = {}));
  36251. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36252. var BABYLON;
  36253. (function (BABYLON) {
  36254. /**
  36255. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36256. */
  36257. var VertexData = /** @class */ (function () {
  36258. function VertexData() {
  36259. }
  36260. /**
  36261. * Uses the passed data array to set the set the values for the specified kind of data
  36262. * @param data a linear array of floating numbers
  36263. * @param kind the type of data that is being set, eg positions, colors etc
  36264. */
  36265. VertexData.prototype.set = function (data, kind) {
  36266. switch (kind) {
  36267. case BABYLON.VertexBuffer.PositionKind:
  36268. this.positions = data;
  36269. break;
  36270. case BABYLON.VertexBuffer.NormalKind:
  36271. this.normals = data;
  36272. break;
  36273. case BABYLON.VertexBuffer.TangentKind:
  36274. this.tangents = data;
  36275. break;
  36276. case BABYLON.VertexBuffer.UVKind:
  36277. this.uvs = data;
  36278. break;
  36279. case BABYLON.VertexBuffer.UV2Kind:
  36280. this.uvs2 = data;
  36281. break;
  36282. case BABYLON.VertexBuffer.UV3Kind:
  36283. this.uvs3 = data;
  36284. break;
  36285. case BABYLON.VertexBuffer.UV4Kind:
  36286. this.uvs4 = data;
  36287. break;
  36288. case BABYLON.VertexBuffer.UV5Kind:
  36289. this.uvs5 = data;
  36290. break;
  36291. case BABYLON.VertexBuffer.UV6Kind:
  36292. this.uvs6 = data;
  36293. break;
  36294. case BABYLON.VertexBuffer.ColorKind:
  36295. this.colors = data;
  36296. break;
  36297. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36298. this.matricesIndices = data;
  36299. break;
  36300. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36301. this.matricesWeights = data;
  36302. break;
  36303. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36304. this.matricesIndicesExtra = data;
  36305. break;
  36306. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36307. this.matricesWeightsExtra = data;
  36308. break;
  36309. }
  36310. };
  36311. /**
  36312. * Associates the vertexData to the passed Mesh.
  36313. * Sets it as updatable or not (default `false`)
  36314. * @param mesh the mesh the vertexData is applied to
  36315. * @param updatable when used and having the value true allows new data to update the vertexData
  36316. * @returns the VertexData
  36317. */
  36318. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36319. this._applyTo(mesh, updatable);
  36320. return this;
  36321. };
  36322. /**
  36323. * Associates the vertexData to the passed Geometry.
  36324. * Sets it as updatable or not (default `false`)
  36325. * @param geometry the geometry the vertexData is applied to
  36326. * @param updatable when used and having the value true allows new data to update the vertexData
  36327. * @returns VertexData
  36328. */
  36329. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36330. this._applyTo(geometry, updatable);
  36331. return this;
  36332. };
  36333. /**
  36334. * Updates the associated mesh
  36335. * @param mesh the mesh to be updated
  36336. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36337. * @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
  36338. * @returns VertexData
  36339. */
  36340. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36341. this._update(mesh);
  36342. return this;
  36343. };
  36344. /**
  36345. * Updates the associated geometry
  36346. * @param geometry the geometry to be updated
  36347. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36348. * @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
  36349. * @returns VertexData.
  36350. */
  36351. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36352. this._update(geometry);
  36353. return this;
  36354. };
  36355. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36356. if (updatable === void 0) { updatable = false; }
  36357. if (this.positions) {
  36358. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36359. }
  36360. if (this.normals) {
  36361. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36362. }
  36363. if (this.tangents) {
  36364. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36365. }
  36366. if (this.uvs) {
  36367. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36368. }
  36369. if (this.uvs2) {
  36370. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36371. }
  36372. if (this.uvs3) {
  36373. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36374. }
  36375. if (this.uvs4) {
  36376. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36377. }
  36378. if (this.uvs5) {
  36379. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36380. }
  36381. if (this.uvs6) {
  36382. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36383. }
  36384. if (this.colors) {
  36385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36386. }
  36387. if (this.matricesIndices) {
  36388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36389. }
  36390. if (this.matricesWeights) {
  36391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36392. }
  36393. if (this.matricesIndicesExtra) {
  36394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36395. }
  36396. if (this.matricesWeightsExtra) {
  36397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36398. }
  36399. if (this.indices) {
  36400. meshOrGeometry.setIndices(this.indices, null, updatable);
  36401. }
  36402. else {
  36403. meshOrGeometry.setIndices([], null);
  36404. }
  36405. return this;
  36406. };
  36407. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36408. if (this.positions) {
  36409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36410. }
  36411. if (this.normals) {
  36412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36413. }
  36414. if (this.tangents) {
  36415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36416. }
  36417. if (this.uvs) {
  36418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36419. }
  36420. if (this.uvs2) {
  36421. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36422. }
  36423. if (this.uvs3) {
  36424. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36425. }
  36426. if (this.uvs4) {
  36427. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36428. }
  36429. if (this.uvs5) {
  36430. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36431. }
  36432. if (this.uvs6) {
  36433. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36434. }
  36435. if (this.colors) {
  36436. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36437. }
  36438. if (this.matricesIndices) {
  36439. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36440. }
  36441. if (this.matricesWeights) {
  36442. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36443. }
  36444. if (this.matricesIndicesExtra) {
  36445. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36446. }
  36447. if (this.matricesWeightsExtra) {
  36448. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36449. }
  36450. if (this.indices) {
  36451. meshOrGeometry.setIndices(this.indices, null);
  36452. }
  36453. return this;
  36454. };
  36455. /**
  36456. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36457. * @param matrix the transforming matrix
  36458. * @returns the VertexData
  36459. */
  36460. VertexData.prototype.transform = function (matrix) {
  36461. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36462. var transformed = BABYLON.Vector3.Zero();
  36463. var index;
  36464. if (this.positions) {
  36465. var position = BABYLON.Vector3.Zero();
  36466. for (index = 0; index < this.positions.length; index += 3) {
  36467. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36468. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36469. this.positions[index] = transformed.x;
  36470. this.positions[index + 1] = transformed.y;
  36471. this.positions[index + 2] = transformed.z;
  36472. }
  36473. }
  36474. if (this.normals) {
  36475. var normal = BABYLON.Vector3.Zero();
  36476. for (index = 0; index < this.normals.length; index += 3) {
  36477. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36478. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36479. this.normals[index] = transformed.x;
  36480. this.normals[index + 1] = transformed.y;
  36481. this.normals[index + 2] = transformed.z;
  36482. }
  36483. }
  36484. if (this.tangents) {
  36485. var tangent = BABYLON.Vector4.Zero();
  36486. var tangentTransformed = BABYLON.Vector4.Zero();
  36487. for (index = 0; index < this.tangents.length; index += 4) {
  36488. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36489. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36490. this.tangents[index] = tangentTransformed.x;
  36491. this.tangents[index + 1] = tangentTransformed.y;
  36492. this.tangents[index + 2] = tangentTransformed.z;
  36493. this.tangents[index + 3] = tangentTransformed.w;
  36494. }
  36495. }
  36496. if (flip && this.indices) {
  36497. for (index = 0; index < this.indices.length; index += 3) {
  36498. var tmp = this.indices[index + 1];
  36499. this.indices[index + 1] = this.indices[index + 2];
  36500. this.indices[index + 2] = tmp;
  36501. }
  36502. }
  36503. return this;
  36504. };
  36505. /**
  36506. * Merges the passed VertexData into the current one
  36507. * @param other the VertexData to be merged into the current one
  36508. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36509. * @returns the modified VertexData
  36510. */
  36511. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36512. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36513. this._validate();
  36514. other._validate();
  36515. if (!this.normals !== !other.normals ||
  36516. !this.tangents !== !other.tangents ||
  36517. !this.uvs !== !other.uvs ||
  36518. !this.uvs2 !== !other.uvs2 ||
  36519. !this.uvs3 !== !other.uvs3 ||
  36520. !this.uvs4 !== !other.uvs4 ||
  36521. !this.uvs5 !== !other.uvs5 ||
  36522. !this.uvs6 !== !other.uvs6 ||
  36523. !this.colors !== !other.colors ||
  36524. !this.matricesIndices !== !other.matricesIndices ||
  36525. !this.matricesWeights !== !other.matricesWeights ||
  36526. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36527. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36528. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36529. }
  36530. if (other.indices) {
  36531. if (!this.indices) {
  36532. this.indices = [];
  36533. }
  36534. var offset = this.positions ? this.positions.length / 3 : 0;
  36535. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36536. if (isSrcTypedArray) {
  36537. var len = this.indices.length + other.indices.length;
  36538. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36539. temp.set(this.indices);
  36540. var decal = this.indices.length;
  36541. for (var index = 0; index < other.indices.length; index++) {
  36542. temp[decal + index] = other.indices[index] + offset;
  36543. }
  36544. this.indices = temp;
  36545. }
  36546. else {
  36547. for (var index = 0; index < other.indices.length; index++) {
  36548. this.indices.push(other.indices[index] + offset);
  36549. }
  36550. }
  36551. }
  36552. this.positions = this._mergeElement(this.positions, other.positions);
  36553. this.normals = this._mergeElement(this.normals, other.normals);
  36554. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36555. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36556. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36557. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36558. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36559. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36560. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36561. this.colors = this._mergeElement(this.colors, other.colors);
  36562. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36563. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36564. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36565. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36566. return this;
  36567. };
  36568. VertexData.prototype._mergeElement = function (source, other) {
  36569. if (!source) {
  36570. return other;
  36571. }
  36572. if (!other) {
  36573. return source;
  36574. }
  36575. var len = other.length + source.length;
  36576. var isSrcTypedArray = source instanceof Float32Array;
  36577. var isOthTypedArray = other instanceof Float32Array;
  36578. // use non-loop method when the source is Float32Array
  36579. if (isSrcTypedArray) {
  36580. var ret32 = new Float32Array(len);
  36581. ret32.set(source);
  36582. ret32.set(other, source.length);
  36583. return ret32;
  36584. // source is number[], when other is also use concat
  36585. }
  36586. else if (!isOthTypedArray) {
  36587. return source.concat(other);
  36588. // source is a number[], but other is a Float32Array, loop required
  36589. }
  36590. else {
  36591. var ret = source.slice(0); // copy source to a separate array
  36592. for (var i = 0, len = other.length; i < len; i++) {
  36593. ret.push(other[i]);
  36594. }
  36595. return ret;
  36596. }
  36597. };
  36598. VertexData.prototype._validate = function () {
  36599. if (!this.positions) {
  36600. throw new Error("Positions are required");
  36601. }
  36602. var getElementCount = function (kind, values) {
  36603. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36604. if ((values.length % stride) !== 0) {
  36605. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36606. }
  36607. return values.length / stride;
  36608. };
  36609. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36610. var validateElementCount = function (kind, values) {
  36611. var elementCount = getElementCount(kind, values);
  36612. if (elementCount !== positionsElementCount) {
  36613. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36614. }
  36615. };
  36616. if (this.normals)
  36617. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36618. if (this.tangents)
  36619. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36620. if (this.uvs)
  36621. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36622. if (this.uvs2)
  36623. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36624. if (this.uvs3)
  36625. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36626. if (this.uvs4)
  36627. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36628. if (this.uvs5)
  36629. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36630. if (this.uvs6)
  36631. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36632. if (this.colors)
  36633. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36634. if (this.matricesIndices)
  36635. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36636. if (this.matricesWeights)
  36637. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36638. if (this.matricesIndicesExtra)
  36639. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36640. if (this.matricesWeightsExtra)
  36641. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36642. };
  36643. /**
  36644. * Serializes the VertexData
  36645. * @returns a serialized object
  36646. */
  36647. VertexData.prototype.serialize = function () {
  36648. var serializationObject = this.serialize();
  36649. if (this.positions) {
  36650. serializationObject.positions = this.positions;
  36651. }
  36652. if (this.normals) {
  36653. serializationObject.normals = this.normals;
  36654. }
  36655. if (this.tangents) {
  36656. serializationObject.tangents = this.tangents;
  36657. }
  36658. if (this.uvs) {
  36659. serializationObject.uvs = this.uvs;
  36660. }
  36661. if (this.uvs2) {
  36662. serializationObject.uvs2 = this.uvs2;
  36663. }
  36664. if (this.uvs3) {
  36665. serializationObject.uvs3 = this.uvs3;
  36666. }
  36667. if (this.uvs4) {
  36668. serializationObject.uvs4 = this.uvs4;
  36669. }
  36670. if (this.uvs5) {
  36671. serializationObject.uvs5 = this.uvs5;
  36672. }
  36673. if (this.uvs6) {
  36674. serializationObject.uvs6 = this.uvs6;
  36675. }
  36676. if (this.colors) {
  36677. serializationObject.colors = this.colors;
  36678. }
  36679. if (this.matricesIndices) {
  36680. serializationObject.matricesIndices = this.matricesIndices;
  36681. serializationObject.matricesIndices._isExpanded = true;
  36682. }
  36683. if (this.matricesWeights) {
  36684. serializationObject.matricesWeights = this.matricesWeights;
  36685. }
  36686. if (this.matricesIndicesExtra) {
  36687. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36688. serializationObject.matricesIndicesExtra._isExpanded = true;
  36689. }
  36690. if (this.matricesWeightsExtra) {
  36691. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36692. }
  36693. serializationObject.indices = this.indices;
  36694. return serializationObject;
  36695. };
  36696. // Statics
  36697. /**
  36698. * Extracts the vertexData from a mesh
  36699. * @param mesh the mesh from which to extract the VertexData
  36700. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36701. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36702. * @returns the object VertexData associated to the passed mesh
  36703. */
  36704. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36705. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36706. };
  36707. /**
  36708. * Extracts the vertexData from the geometry
  36709. * @param geometry the geometry from which to extract the VertexData
  36710. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36711. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36712. * @returns the object VertexData associated to the passed mesh
  36713. */
  36714. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36715. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36716. };
  36717. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36718. var result = new VertexData();
  36719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36720. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36721. }
  36722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36723. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36724. }
  36725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36726. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36727. }
  36728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36729. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36730. }
  36731. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36732. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36733. }
  36734. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36735. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36736. }
  36737. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36738. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36739. }
  36740. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36741. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36742. }
  36743. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36744. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36745. }
  36746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36747. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36748. }
  36749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36750. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36751. }
  36752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36753. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36754. }
  36755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36756. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36757. }
  36758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36759. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36760. }
  36761. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36762. return result;
  36763. };
  36764. /**
  36765. * Creates the VertexData for a Ribbon
  36766. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36767. * * pathArray array of paths, each of which an array of successive Vector3
  36768. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36769. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36770. * * 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
  36771. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36772. * * 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)
  36773. * * 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)
  36774. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36775. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36776. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36777. * @returns the VertexData of the ribbon
  36778. */
  36779. VertexData.CreateRibbon = function (options) {
  36780. var pathArray = options.pathArray;
  36781. var closeArray = options.closeArray || false;
  36782. var closePath = options.closePath || false;
  36783. var invertUV = options.invertUV || false;
  36784. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36785. var offset = options.offset || defaultOffset;
  36786. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36787. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36788. var customUV = options.uvs;
  36789. var customColors = options.colors;
  36790. var positions = [];
  36791. var indices = [];
  36792. var normals = [];
  36793. var uvs = [];
  36794. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36795. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36796. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36797. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36798. var minlg; // minimal length among all paths from pathArray
  36799. var lg = []; // array of path lengths : nb of vertex per path
  36800. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36801. var p; // path iterator
  36802. var i; // point iterator
  36803. var j; // point iterator
  36804. // if single path in pathArray
  36805. if (pathArray.length < 2) {
  36806. var ar1 = [];
  36807. var ar2 = [];
  36808. for (i = 0; i < pathArray[0].length - offset; i++) {
  36809. ar1.push(pathArray[0][i]);
  36810. ar2.push(pathArray[0][i + offset]);
  36811. }
  36812. pathArray = [ar1, ar2];
  36813. }
  36814. // positions and horizontal distances (u)
  36815. var idc = 0;
  36816. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36817. var path;
  36818. var l;
  36819. minlg = pathArray[0].length;
  36820. var vectlg;
  36821. var dist;
  36822. for (p = 0; p < pathArray.length; p++) {
  36823. uTotalDistance[p] = 0;
  36824. us[p] = [0];
  36825. path = pathArray[p];
  36826. l = path.length;
  36827. minlg = (minlg < l) ? minlg : l;
  36828. j = 0;
  36829. while (j < l) {
  36830. positions.push(path[j].x, path[j].y, path[j].z);
  36831. if (j > 0) {
  36832. vectlg = path[j].subtract(path[j - 1]).length();
  36833. dist = vectlg + uTotalDistance[p];
  36834. us[p].push(dist);
  36835. uTotalDistance[p] = dist;
  36836. }
  36837. j++;
  36838. }
  36839. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36840. j--;
  36841. positions.push(path[0].x, path[0].y, path[0].z);
  36842. vectlg = path[j].subtract(path[0]).length();
  36843. dist = vectlg + uTotalDistance[p];
  36844. us[p].push(dist);
  36845. uTotalDistance[p] = dist;
  36846. }
  36847. lg[p] = l + closePathCorr;
  36848. idx[p] = idc;
  36849. idc += (l + closePathCorr);
  36850. }
  36851. // vertical distances (v)
  36852. var path1;
  36853. var path2;
  36854. var vertex1 = null;
  36855. var vertex2 = null;
  36856. for (i = 0; i < minlg + closePathCorr; i++) {
  36857. vTotalDistance[i] = 0;
  36858. vs[i] = [0];
  36859. for (p = 0; p < pathArray.length - 1; p++) {
  36860. path1 = pathArray[p];
  36861. path2 = pathArray[p + 1];
  36862. if (i === minlg) { // closePath
  36863. vertex1 = path1[0];
  36864. vertex2 = path2[0];
  36865. }
  36866. else {
  36867. vertex1 = path1[i];
  36868. vertex2 = path2[i];
  36869. }
  36870. vectlg = vertex2.subtract(vertex1).length();
  36871. dist = vectlg + vTotalDistance[i];
  36872. vs[i].push(dist);
  36873. vTotalDistance[i] = dist;
  36874. }
  36875. if (closeArray && vertex2 && vertex1) {
  36876. path1 = pathArray[p];
  36877. path2 = pathArray[0];
  36878. if (i === minlg) { // closePath
  36879. vertex2 = path2[0];
  36880. }
  36881. vectlg = vertex2.subtract(vertex1).length();
  36882. dist = vectlg + vTotalDistance[i];
  36883. vTotalDistance[i] = dist;
  36884. }
  36885. }
  36886. // uvs
  36887. var u;
  36888. var v;
  36889. if (customUV) {
  36890. for (p = 0; p < customUV.length; p++) {
  36891. uvs.push(customUV[p].x, customUV[p].y);
  36892. }
  36893. }
  36894. else {
  36895. for (p = 0; p < pathArray.length; p++) {
  36896. for (i = 0; i < minlg + closePathCorr; i++) {
  36897. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36898. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36899. if (invertUV) {
  36900. uvs.push(v, u);
  36901. }
  36902. else {
  36903. uvs.push(u, v);
  36904. }
  36905. }
  36906. }
  36907. }
  36908. // indices
  36909. p = 0; // path index
  36910. var pi = 0; // positions array index
  36911. var l1 = lg[p] - 1; // path1 length
  36912. var l2 = lg[p + 1] - 1; // path2 length
  36913. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36914. var shft = idx[1] - idx[0]; // shift
  36915. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36916. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36917. // 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
  36918. indices.push(pi, pi + shft, pi + 1);
  36919. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36920. pi += 1;
  36921. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36922. p++;
  36923. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36924. shft = idx[0] - idx[p];
  36925. l1 = lg[p] - 1;
  36926. l2 = lg[0] - 1;
  36927. }
  36928. else {
  36929. shft = idx[p + 1] - idx[p];
  36930. l1 = lg[p] - 1;
  36931. l2 = lg[p + 1] - 1;
  36932. }
  36933. pi = idx[p];
  36934. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36935. }
  36936. }
  36937. // normals
  36938. VertexData.ComputeNormals(positions, indices, normals);
  36939. if (closePath) { // update both the first and last vertex normals to their average value
  36940. var indexFirst = 0;
  36941. var indexLast = 0;
  36942. for (p = 0; p < pathArray.length; p++) {
  36943. indexFirst = idx[p] * 3;
  36944. if (p + 1 < pathArray.length) {
  36945. indexLast = (idx[p + 1] - 1) * 3;
  36946. }
  36947. else {
  36948. indexLast = normals.length - 3;
  36949. }
  36950. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36951. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36952. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36953. normals[indexLast] = normals[indexFirst];
  36954. normals[indexLast + 1] = normals[indexFirst + 1];
  36955. normals[indexLast + 2] = normals[indexFirst + 2];
  36956. }
  36957. }
  36958. // sides
  36959. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36960. // Colors
  36961. var colors = null;
  36962. if (customColors) {
  36963. colors = new Float32Array(customColors.length * 4);
  36964. for (var c = 0; c < customColors.length; c++) {
  36965. colors[c * 4] = customColors[c].r;
  36966. colors[c * 4 + 1] = customColors[c].g;
  36967. colors[c * 4 + 2] = customColors[c].b;
  36968. colors[c * 4 + 3] = customColors[c].a;
  36969. }
  36970. }
  36971. // Result
  36972. var vertexData = new VertexData();
  36973. var positions32 = new Float32Array(positions);
  36974. var normals32 = new Float32Array(normals);
  36975. var uvs32 = new Float32Array(uvs);
  36976. vertexData.indices = indices;
  36977. vertexData.positions = positions32;
  36978. vertexData.normals = normals32;
  36979. vertexData.uvs = uvs32;
  36980. if (colors) {
  36981. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36982. }
  36983. if (closePath) {
  36984. vertexData._idx = idx;
  36985. }
  36986. return vertexData;
  36987. };
  36988. /**
  36989. * Creates the VertexData for a box
  36990. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36991. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36992. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36993. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36994. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36995. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36996. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36997. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36998. * * 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)
  36999. * * 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)
  37000. * @returns the VertexData of the box
  37001. */
  37002. VertexData.CreateBox = function (options) {
  37003. var normalsSource = [
  37004. new BABYLON.Vector3(0, 0, 1),
  37005. new BABYLON.Vector3(0, 0, -1),
  37006. new BABYLON.Vector3(1, 0, 0),
  37007. new BABYLON.Vector3(-1, 0, 0),
  37008. new BABYLON.Vector3(0, 1, 0),
  37009. new BABYLON.Vector3(0, -1, 0)
  37010. ];
  37011. var indices = [];
  37012. var positions = [];
  37013. var normals = [];
  37014. var uvs = [];
  37015. var width = options.width || options.size || 1;
  37016. var height = options.height || options.size || 1;
  37017. var depth = options.depth || options.size || 1;
  37018. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37019. var faceUV = options.faceUV || new Array(6);
  37020. var faceColors = options.faceColors;
  37021. var colors = [];
  37022. // default face colors and UV if undefined
  37023. for (var f = 0; f < 6; f++) {
  37024. if (faceUV[f] === undefined) {
  37025. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37026. }
  37027. if (faceColors && faceColors[f] === undefined) {
  37028. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37029. }
  37030. }
  37031. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37032. // Create each face in turn.
  37033. for (var index = 0; index < normalsSource.length; index++) {
  37034. var normal = normalsSource[index];
  37035. // Get two vectors perpendicular to the face normal and to each other.
  37036. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37037. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37038. // Six indices (two triangles) per face.
  37039. var verticesLength = positions.length / 3;
  37040. indices.push(verticesLength);
  37041. indices.push(verticesLength + 1);
  37042. indices.push(verticesLength + 2);
  37043. indices.push(verticesLength);
  37044. indices.push(verticesLength + 2);
  37045. indices.push(verticesLength + 3);
  37046. // Four vertices per face.
  37047. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37048. positions.push(vertex.x, vertex.y, vertex.z);
  37049. normals.push(normal.x, normal.y, normal.z);
  37050. uvs.push(faceUV[index].z, faceUV[index].w);
  37051. if (faceColors) {
  37052. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37053. }
  37054. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37055. positions.push(vertex.x, vertex.y, vertex.z);
  37056. normals.push(normal.x, normal.y, normal.z);
  37057. uvs.push(faceUV[index].x, faceUV[index].w);
  37058. if (faceColors) {
  37059. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37060. }
  37061. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37062. positions.push(vertex.x, vertex.y, vertex.z);
  37063. normals.push(normal.x, normal.y, normal.z);
  37064. uvs.push(faceUV[index].x, faceUV[index].y);
  37065. if (faceColors) {
  37066. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37067. }
  37068. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37069. positions.push(vertex.x, vertex.y, vertex.z);
  37070. normals.push(normal.x, normal.y, normal.z);
  37071. uvs.push(faceUV[index].z, faceUV[index].y);
  37072. if (faceColors) {
  37073. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37074. }
  37075. }
  37076. // sides
  37077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37078. // Result
  37079. var vertexData = new VertexData();
  37080. vertexData.indices = indices;
  37081. vertexData.positions = positions;
  37082. vertexData.normals = normals;
  37083. vertexData.uvs = uvs;
  37084. if (faceColors) {
  37085. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37086. vertexData.colors = totalColors;
  37087. }
  37088. return vertexData;
  37089. };
  37090. /**
  37091. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37092. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37093. * * segments sets the number of horizontal strips optional, default 32
  37094. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37095. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37096. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37097. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37098. * * 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
  37099. * * 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
  37100. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37101. * * 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)
  37102. * * 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)
  37103. * @returns the VertexData of the ellipsoid
  37104. */
  37105. VertexData.CreateSphere = function (options) {
  37106. var segments = options.segments || 32;
  37107. var diameterX = options.diameterX || options.diameter || 1;
  37108. var diameterY = options.diameterY || options.diameter || 1;
  37109. var diameterZ = options.diameterZ || options.diameter || 1;
  37110. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37111. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37112. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37113. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37114. var totalZRotationSteps = 2 + segments;
  37115. var totalYRotationSteps = 2 * totalZRotationSteps;
  37116. var indices = [];
  37117. var positions = [];
  37118. var normals = [];
  37119. var uvs = [];
  37120. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37121. var normalizedZ = zRotationStep / totalZRotationSteps;
  37122. var angleZ = normalizedZ * Math.PI * slice;
  37123. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37124. var normalizedY = yRotationStep / totalYRotationSteps;
  37125. var angleY = normalizedY * Math.PI * 2 * arc;
  37126. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37127. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37128. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37129. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37130. var vertex = complete.multiply(radius);
  37131. var normal = complete.divide(radius).normalize();
  37132. positions.push(vertex.x, vertex.y, vertex.z);
  37133. normals.push(normal.x, normal.y, normal.z);
  37134. uvs.push(normalizedY, normalizedZ);
  37135. }
  37136. if (zRotationStep > 0) {
  37137. var verticesCount = positions.length / 3;
  37138. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37139. indices.push((firstIndex));
  37140. indices.push((firstIndex + 1));
  37141. indices.push(firstIndex + totalYRotationSteps + 1);
  37142. indices.push((firstIndex + totalYRotationSteps + 1));
  37143. indices.push((firstIndex + 1));
  37144. indices.push((firstIndex + totalYRotationSteps + 2));
  37145. }
  37146. }
  37147. }
  37148. // Sides
  37149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37150. // Result
  37151. var vertexData = new VertexData();
  37152. vertexData.indices = indices;
  37153. vertexData.positions = positions;
  37154. vertexData.normals = normals;
  37155. vertexData.uvs = uvs;
  37156. return vertexData;
  37157. };
  37158. /**
  37159. * Creates the VertexData for a cylinder, cone or prism
  37160. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37161. * * height sets the height (y direction) of the cylinder, optional, default 2
  37162. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37163. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37164. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37165. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37166. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37167. * * 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
  37168. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37169. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37170. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37171. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37172. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37173. * * 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)
  37174. * * 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)
  37175. * @returns the VertexData of the cylinder, cone or prism
  37176. */
  37177. VertexData.CreateCylinder = function (options) {
  37178. var height = options.height || 2;
  37179. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37180. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37181. var tessellation = options.tessellation || 24;
  37182. var subdivisions = options.subdivisions || 1;
  37183. var hasRings = options.hasRings ? true : false;
  37184. var enclose = options.enclose ? true : false;
  37185. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37186. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37187. var faceUV = options.faceUV || new Array(3);
  37188. var faceColors = options.faceColors;
  37189. // default face colors and UV if undefined
  37190. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37191. var ringNb = (hasRings) ? subdivisions : 1;
  37192. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37193. var f;
  37194. for (f = 0; f < surfaceNb; f++) {
  37195. if (faceColors && faceColors[f] === undefined) {
  37196. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37197. }
  37198. }
  37199. for (f = 0; f < surfaceNb; f++) {
  37200. if (faceUV && faceUV[f] === undefined) {
  37201. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37202. }
  37203. }
  37204. var indices = new Array();
  37205. var positions = new Array();
  37206. var normals = new Array();
  37207. var uvs = new Array();
  37208. var colors = new Array();
  37209. var angle_step = Math.PI * 2 * arc / tessellation;
  37210. var angle;
  37211. var h;
  37212. var radius;
  37213. var tan = (diameterBottom - diameterTop) / 2 / height;
  37214. var ringVertex = BABYLON.Vector3.Zero();
  37215. var ringNormal = BABYLON.Vector3.Zero();
  37216. var ringFirstVertex = BABYLON.Vector3.Zero();
  37217. var ringFirstNormal = BABYLON.Vector3.Zero();
  37218. var quadNormal = BABYLON.Vector3.Zero();
  37219. var Y = BABYLON.Axis.Y;
  37220. // positions, normals, uvs
  37221. var i;
  37222. var j;
  37223. var r;
  37224. var ringIdx = 1;
  37225. var s = 1; // surface index
  37226. var cs = 0;
  37227. var v = 0;
  37228. for (i = 0; i <= subdivisions; i++) {
  37229. h = i / subdivisions;
  37230. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37231. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37232. for (r = 0; r < ringIdx; r++) {
  37233. if (hasRings) {
  37234. s += r;
  37235. }
  37236. if (enclose) {
  37237. s += 2 * r;
  37238. }
  37239. for (j = 0; j <= tessellation; j++) {
  37240. angle = j * angle_step;
  37241. // position
  37242. ringVertex.x = Math.cos(-angle) * radius;
  37243. ringVertex.y = -height / 2 + h * height;
  37244. ringVertex.z = Math.sin(-angle) * radius;
  37245. // normal
  37246. if (diameterTop === 0 && i === subdivisions) {
  37247. // if no top cap, reuse former normals
  37248. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37249. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37250. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37251. }
  37252. else {
  37253. ringNormal.x = ringVertex.x;
  37254. ringNormal.z = ringVertex.z;
  37255. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37256. ringNormal.normalize();
  37257. }
  37258. // keep first ring vertex values for enclose
  37259. if (j === 0) {
  37260. ringFirstVertex.copyFrom(ringVertex);
  37261. ringFirstNormal.copyFrom(ringNormal);
  37262. }
  37263. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37264. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37265. if (hasRings) {
  37266. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37267. }
  37268. else {
  37269. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37270. }
  37271. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37272. if (faceColors) {
  37273. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37274. }
  37275. }
  37276. // if enclose, add four vertices and their dedicated normals
  37277. if (arc !== 1 && enclose) {
  37278. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37279. positions.push(0, ringVertex.y, 0);
  37280. positions.push(0, ringVertex.y, 0);
  37281. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37282. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37283. quadNormal.normalize();
  37284. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37285. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37286. quadNormal.normalize();
  37287. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37288. if (hasRings) {
  37289. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37290. }
  37291. else {
  37292. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37293. }
  37294. uvs.push(faceUV[s + 1].x, v);
  37295. uvs.push(faceUV[s + 1].z, v);
  37296. if (hasRings) {
  37297. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37298. }
  37299. else {
  37300. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37301. }
  37302. uvs.push(faceUV[s + 2].x, v);
  37303. uvs.push(faceUV[s + 2].z, v);
  37304. if (faceColors) {
  37305. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37306. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37307. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37308. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37309. }
  37310. }
  37311. if (cs !== s) {
  37312. cs = s;
  37313. }
  37314. }
  37315. }
  37316. // indices
  37317. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37318. var s;
  37319. i = 0;
  37320. for (s = 0; s < subdivisions; s++) {
  37321. var i0 = 0;
  37322. var i1 = 0;
  37323. var i2 = 0;
  37324. var i3 = 0;
  37325. for (j = 0; j < tessellation; j++) {
  37326. i0 = i * (e + 1) + j;
  37327. i1 = (i + 1) * (e + 1) + j;
  37328. i2 = i * (e + 1) + (j + 1);
  37329. i3 = (i + 1) * (e + 1) + (j + 1);
  37330. indices.push(i0, i1, i2);
  37331. indices.push(i3, i2, i1);
  37332. }
  37333. if (arc !== 1 && enclose) { // if enclose, add two quads
  37334. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37335. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37336. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37337. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37338. }
  37339. i = (hasRings) ? (i + 2) : (i + 1);
  37340. }
  37341. // Caps
  37342. var createCylinderCap = function (isTop) {
  37343. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37344. if (radius === 0) {
  37345. return;
  37346. }
  37347. // Cap positions, normals & uvs
  37348. var angle;
  37349. var circleVector;
  37350. var i;
  37351. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37352. var c = null;
  37353. if (faceColors) {
  37354. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37355. }
  37356. // cap center
  37357. var vbase = positions.length / 3;
  37358. var offset = isTop ? height / 2 : -height / 2;
  37359. var center = new BABYLON.Vector3(0, offset, 0);
  37360. positions.push(center.x, center.y, center.z);
  37361. normals.push(0, isTop ? 1 : -1, 0);
  37362. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37363. if (c) {
  37364. colors.push(c.r, c.g, c.b, c.a);
  37365. }
  37366. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37367. for (i = 0; i <= tessellation; i++) {
  37368. angle = Math.PI * 2 * i * arc / tessellation;
  37369. var cos = Math.cos(-angle);
  37370. var sin = Math.sin(-angle);
  37371. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37372. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37373. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37374. normals.push(0, isTop ? 1 : -1, 0);
  37375. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37376. if (c) {
  37377. colors.push(c.r, c.g, c.b, c.a);
  37378. }
  37379. }
  37380. // Cap indices
  37381. for (i = 0; i < tessellation; i++) {
  37382. if (!isTop) {
  37383. indices.push(vbase);
  37384. indices.push(vbase + (i + 1));
  37385. indices.push(vbase + (i + 2));
  37386. }
  37387. else {
  37388. indices.push(vbase);
  37389. indices.push(vbase + (i + 2));
  37390. indices.push(vbase + (i + 1));
  37391. }
  37392. }
  37393. };
  37394. // add caps to geometry
  37395. createCylinderCap(false);
  37396. createCylinderCap(true);
  37397. // Sides
  37398. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37399. var vertexData = new VertexData();
  37400. vertexData.indices = indices;
  37401. vertexData.positions = positions;
  37402. vertexData.normals = normals;
  37403. vertexData.uvs = uvs;
  37404. if (faceColors) {
  37405. vertexData.colors = colors;
  37406. }
  37407. return vertexData;
  37408. };
  37409. /**
  37410. * Creates the VertexData for a torus
  37411. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37412. * * diameter the diameter of the torus, optional default 1
  37413. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37414. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37415. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37416. * * 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)
  37417. * * 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)
  37418. * @returns the VertexData of the torus
  37419. */
  37420. VertexData.CreateTorus = function (options) {
  37421. var indices = [];
  37422. var positions = [];
  37423. var normals = [];
  37424. var uvs = [];
  37425. var diameter = options.diameter || 1;
  37426. var thickness = options.thickness || 0.5;
  37427. var tessellation = options.tessellation || 16;
  37428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37429. var stride = tessellation + 1;
  37430. for (var i = 0; i <= tessellation; i++) {
  37431. var u = i / tessellation;
  37432. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37433. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37434. for (var j = 0; j <= tessellation; j++) {
  37435. var v = 1 - j / tessellation;
  37436. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37437. var dx = Math.cos(innerAngle);
  37438. var dy = Math.sin(innerAngle);
  37439. // Create a vertex.
  37440. var normal = new BABYLON.Vector3(dx, dy, 0);
  37441. var position = normal.scale(thickness / 2);
  37442. var textureCoordinate = new BABYLON.Vector2(u, v);
  37443. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37444. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37445. positions.push(position.x, position.y, position.z);
  37446. normals.push(normal.x, normal.y, normal.z);
  37447. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37448. // And create indices for two triangles.
  37449. var nextI = (i + 1) % stride;
  37450. var nextJ = (j + 1) % stride;
  37451. indices.push(i * stride + j);
  37452. indices.push(i * stride + nextJ);
  37453. indices.push(nextI * stride + j);
  37454. indices.push(i * stride + nextJ);
  37455. indices.push(nextI * stride + nextJ);
  37456. indices.push(nextI * stride + j);
  37457. }
  37458. }
  37459. // Sides
  37460. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37461. // Result
  37462. var vertexData = new VertexData();
  37463. vertexData.indices = indices;
  37464. vertexData.positions = positions;
  37465. vertexData.normals = normals;
  37466. vertexData.uvs = uvs;
  37467. return vertexData;
  37468. };
  37469. /**
  37470. * Creates the VertexData of the LineSystem
  37471. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37472. * - lines an array of lines, each line being an array of successive Vector3
  37473. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37474. * @returns the VertexData of the LineSystem
  37475. */
  37476. VertexData.CreateLineSystem = function (options) {
  37477. var indices = [];
  37478. var positions = [];
  37479. var lines = options.lines;
  37480. var colors = options.colors;
  37481. var vertexColors = [];
  37482. var idx = 0;
  37483. for (var l = 0; l < lines.length; l++) {
  37484. var points = lines[l];
  37485. for (var index = 0; index < points.length; index++) {
  37486. positions.push(points[index].x, points[index].y, points[index].z);
  37487. if (colors) {
  37488. var color = colors[l];
  37489. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37490. }
  37491. if (index > 0) {
  37492. indices.push(idx - 1);
  37493. indices.push(idx);
  37494. }
  37495. idx++;
  37496. }
  37497. }
  37498. var vertexData = new VertexData();
  37499. vertexData.indices = indices;
  37500. vertexData.positions = positions;
  37501. if (colors) {
  37502. vertexData.colors = vertexColors;
  37503. }
  37504. return vertexData;
  37505. };
  37506. /**
  37507. * Create the VertexData for a DashedLines
  37508. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37509. * - points an array successive Vector3
  37510. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37511. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37512. * - dashNb the intended total number of dashes, optional, default 200
  37513. * @returns the VertexData for the DashedLines
  37514. */
  37515. VertexData.CreateDashedLines = function (options) {
  37516. var dashSize = options.dashSize || 3;
  37517. var gapSize = options.gapSize || 1;
  37518. var dashNb = options.dashNb || 200;
  37519. var points = options.points;
  37520. var positions = new Array();
  37521. var indices = new Array();
  37522. var curvect = BABYLON.Vector3.Zero();
  37523. var lg = 0;
  37524. var nb = 0;
  37525. var shft = 0;
  37526. var dashshft = 0;
  37527. var curshft = 0;
  37528. var idx = 0;
  37529. var i = 0;
  37530. for (i = 0; i < points.length - 1; i++) {
  37531. points[i + 1].subtractToRef(points[i], curvect);
  37532. lg += curvect.length();
  37533. }
  37534. shft = lg / dashNb;
  37535. dashshft = dashSize * shft / (dashSize + gapSize);
  37536. for (i = 0; i < points.length - 1; i++) {
  37537. points[i + 1].subtractToRef(points[i], curvect);
  37538. nb = Math.floor(curvect.length() / shft);
  37539. curvect.normalize();
  37540. for (var j = 0; j < nb; j++) {
  37541. curshft = shft * j;
  37542. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37543. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37544. indices.push(idx, idx + 1);
  37545. idx += 2;
  37546. }
  37547. }
  37548. // Result
  37549. var vertexData = new VertexData();
  37550. vertexData.positions = positions;
  37551. vertexData.indices = indices;
  37552. return vertexData;
  37553. };
  37554. /**
  37555. * Creates the VertexData for a Ground
  37556. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37557. * - width the width (x direction) of the ground, optional, default 1
  37558. * - height the height (z direction) of the ground, optional, default 1
  37559. * - subdivisions the number of subdivisions per side, optional, default 1
  37560. * @returns the VertexData of the Ground
  37561. */
  37562. VertexData.CreateGround = function (options) {
  37563. var indices = [];
  37564. var positions = [];
  37565. var normals = [];
  37566. var uvs = [];
  37567. var row, col;
  37568. var width = options.width || 1;
  37569. var height = options.height || 1;
  37570. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37571. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37572. for (row = 0; row <= subdivisionsY; row++) {
  37573. for (col = 0; col <= subdivisionsX; col++) {
  37574. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37575. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37576. positions.push(position.x, position.y, position.z);
  37577. normals.push(normal.x, normal.y, normal.z);
  37578. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37579. }
  37580. }
  37581. for (row = 0; row < subdivisionsY; row++) {
  37582. for (col = 0; col < subdivisionsX; col++) {
  37583. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37584. indices.push(col + 1 + row * (subdivisionsX + 1));
  37585. indices.push(col + row * (subdivisionsX + 1));
  37586. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37587. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37588. indices.push(col + row * (subdivisionsX + 1));
  37589. }
  37590. }
  37591. // Result
  37592. var vertexData = new VertexData();
  37593. vertexData.indices = indices;
  37594. vertexData.positions = positions;
  37595. vertexData.normals = normals;
  37596. vertexData.uvs = uvs;
  37597. return vertexData;
  37598. };
  37599. /**
  37600. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37601. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37602. * * xmin the ground minimum X coordinate, optional, default -1
  37603. * * zmin the ground minimum Z coordinate, optional, default -1
  37604. * * xmax the ground maximum X coordinate, optional, default 1
  37605. * * zmax the ground maximum Z coordinate, optional, default 1
  37606. * * 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}
  37607. * * 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}
  37608. * @returns the VertexData of the TiledGround
  37609. */
  37610. VertexData.CreateTiledGround = function (options) {
  37611. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37612. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37613. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37614. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37615. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37616. var precision = options.precision || { w: 1, h: 1 };
  37617. var indices = new Array();
  37618. var positions = new Array();
  37619. var normals = new Array();
  37620. var uvs = new Array();
  37621. var row, col, tileRow, tileCol;
  37622. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37623. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37624. precision.w = (precision.w < 1) ? 1 : precision.w;
  37625. precision.h = (precision.h < 1) ? 1 : precision.h;
  37626. var tileSize = {
  37627. 'w': (xmax - xmin) / subdivisions.w,
  37628. 'h': (zmax - zmin) / subdivisions.h
  37629. };
  37630. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37631. // Indices
  37632. var base = positions.length / 3;
  37633. var rowLength = precision.w + 1;
  37634. for (row = 0; row < precision.h; row++) {
  37635. for (col = 0; col < precision.w; col++) {
  37636. var square = [
  37637. base + col + row * rowLength,
  37638. base + (col + 1) + row * rowLength,
  37639. base + (col + 1) + (row + 1) * rowLength,
  37640. base + col + (row + 1) * rowLength
  37641. ];
  37642. indices.push(square[1]);
  37643. indices.push(square[2]);
  37644. indices.push(square[3]);
  37645. indices.push(square[0]);
  37646. indices.push(square[1]);
  37647. indices.push(square[3]);
  37648. }
  37649. }
  37650. // Position, normals and uvs
  37651. var position = BABYLON.Vector3.Zero();
  37652. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37653. for (row = 0; row <= precision.h; row++) {
  37654. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37655. for (col = 0; col <= precision.w; col++) {
  37656. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37657. position.y = 0;
  37658. positions.push(position.x, position.y, position.z);
  37659. normals.push(normal.x, normal.y, normal.z);
  37660. uvs.push(col / precision.w, row / precision.h);
  37661. }
  37662. }
  37663. }
  37664. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37665. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37666. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37667. }
  37668. }
  37669. // Result
  37670. var vertexData = new VertexData();
  37671. vertexData.indices = indices;
  37672. vertexData.positions = positions;
  37673. vertexData.normals = normals;
  37674. vertexData.uvs = uvs;
  37675. return vertexData;
  37676. };
  37677. /**
  37678. * Creates the VertexData of the Ground designed from a heightmap
  37679. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37680. * * width the width (x direction) of the ground
  37681. * * height the height (z direction) of the ground
  37682. * * subdivisions the number of subdivisions per side
  37683. * * minHeight the minimum altitude on the ground, optional, default 0
  37684. * * maxHeight the maximum altitude on the ground, optional default 1
  37685. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37686. * * buffer the array holding the image color data
  37687. * * bufferWidth the width of image
  37688. * * bufferHeight the height of image
  37689. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37690. * @returns the VertexData of the Ground designed from a heightmap
  37691. */
  37692. VertexData.CreateGroundFromHeightMap = function (options) {
  37693. var indices = [];
  37694. var positions = [];
  37695. var normals = [];
  37696. var uvs = [];
  37697. var row, col;
  37698. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37699. var alphaFilter = options.alphaFilter || 0.0;
  37700. // Vertices
  37701. for (row = 0; row <= options.subdivisions; row++) {
  37702. for (col = 0; col <= options.subdivisions; col++) {
  37703. 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));
  37704. // Compute height
  37705. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37706. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37707. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37708. var r = options.buffer[pos] / 255.0;
  37709. var g = options.buffer[pos + 1] / 255.0;
  37710. var b = options.buffer[pos + 2] / 255.0;
  37711. var a = options.buffer[pos + 3] / 255.0;
  37712. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37713. // If our alpha channel is not within our filter then we will assign a 'special' height
  37714. // Then when building the indices, we will ignore any vertex that is using the special height
  37715. if (a >= alphaFilter)
  37716. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37717. else {
  37718. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37719. }
  37720. // Add vertex
  37721. positions.push(position.x, position.y, position.z);
  37722. normals.push(0, 0, 0);
  37723. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37724. }
  37725. }
  37726. // Indices
  37727. for (row = 0; row < options.subdivisions; row++) {
  37728. for (col = 0; col < options.subdivisions; col++) {
  37729. // Calculate Indices
  37730. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37731. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37732. var idx3 = (col + row * (options.subdivisions + 1));
  37733. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37734. // Check that all indices are visible (based on our special height)
  37735. // Only display the vertex if all Indices are visible
  37736. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37737. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37738. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37739. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37740. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37741. indices.push(idx1);
  37742. indices.push(idx2);
  37743. indices.push(idx3);
  37744. }
  37745. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37746. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37747. indices.push(idx4);
  37748. indices.push(idx1);
  37749. indices.push(idx3);
  37750. }
  37751. }
  37752. }
  37753. // Normals
  37754. VertexData.ComputeNormals(positions, indices, normals);
  37755. // Result
  37756. var vertexData = new VertexData();
  37757. vertexData.indices = indices;
  37758. vertexData.positions = positions;
  37759. vertexData.normals = normals;
  37760. vertexData.uvs = uvs;
  37761. return vertexData;
  37762. };
  37763. /**
  37764. * Creates the VertexData for a Plane
  37765. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37766. * * size sets the width and height of the plane to the value of size, optional default 1
  37767. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37768. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37769. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37770. * * 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)
  37771. * * 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)
  37772. * @returns the VertexData of the box
  37773. */
  37774. VertexData.CreatePlane = function (options) {
  37775. var indices = [];
  37776. var positions = [];
  37777. var normals = [];
  37778. var uvs = [];
  37779. var width = options.width || options.size || 1;
  37780. var height = options.height || options.size || 1;
  37781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37782. // Vertices
  37783. var halfWidth = width / 2.0;
  37784. var halfHeight = height / 2.0;
  37785. positions.push(-halfWidth, -halfHeight, 0);
  37786. normals.push(0, 0, -1.0);
  37787. uvs.push(0.0, 0.0);
  37788. positions.push(halfWidth, -halfHeight, 0);
  37789. normals.push(0, 0, -1.0);
  37790. uvs.push(1.0, 0.0);
  37791. positions.push(halfWidth, halfHeight, 0);
  37792. normals.push(0, 0, -1.0);
  37793. uvs.push(1.0, 1.0);
  37794. positions.push(-halfWidth, halfHeight, 0);
  37795. normals.push(0, 0, -1.0);
  37796. uvs.push(0.0, 1.0);
  37797. // Indices
  37798. indices.push(0);
  37799. indices.push(1);
  37800. indices.push(2);
  37801. indices.push(0);
  37802. indices.push(2);
  37803. indices.push(3);
  37804. // Sides
  37805. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37806. // Result
  37807. var vertexData = new VertexData();
  37808. vertexData.indices = indices;
  37809. vertexData.positions = positions;
  37810. vertexData.normals = normals;
  37811. vertexData.uvs = uvs;
  37812. return vertexData;
  37813. };
  37814. /**
  37815. * Creates the VertexData of the Disc or regular Polygon
  37816. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37817. * * radius the radius of the disc, optional default 0.5
  37818. * * tessellation the number of polygon sides, optional, default 64
  37819. * * 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
  37820. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37821. * * 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)
  37822. * * 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)
  37823. * @returns the VertexData of the box
  37824. */
  37825. VertexData.CreateDisc = function (options) {
  37826. var positions = new Array();
  37827. var indices = new Array();
  37828. var normals = new Array();
  37829. var uvs = new Array();
  37830. var radius = options.radius || 0.5;
  37831. var tessellation = options.tessellation || 64;
  37832. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37833. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37834. // positions and uvs
  37835. positions.push(0, 0, 0); // disc center first
  37836. uvs.push(0.5, 0.5);
  37837. var theta = Math.PI * 2 * arc;
  37838. var step = theta / tessellation;
  37839. for (var a = 0; a < theta; a += step) {
  37840. var x = Math.cos(a);
  37841. var y = Math.sin(a);
  37842. var u = (x + 1) / 2;
  37843. var v = (1 - y) / 2;
  37844. positions.push(radius * x, radius * y, 0);
  37845. uvs.push(u, v);
  37846. }
  37847. if (arc === 1) {
  37848. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37849. uvs.push(uvs[2], uvs[3]);
  37850. }
  37851. //indices
  37852. var vertexNb = positions.length / 3;
  37853. for (var i = 1; i < vertexNb - 1; i++) {
  37854. indices.push(i + 1, 0, i);
  37855. }
  37856. // result
  37857. VertexData.ComputeNormals(positions, indices, normals);
  37858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37859. var vertexData = new VertexData();
  37860. vertexData.indices = indices;
  37861. vertexData.positions = positions;
  37862. vertexData.normals = normals;
  37863. vertexData.uvs = uvs;
  37864. return vertexData;
  37865. };
  37866. /**
  37867. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37868. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37869. * @param polygon a mesh built from polygonTriangulation.build()
  37870. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37871. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37872. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37873. * @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)
  37874. * @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)
  37875. * @returns the VertexData of the Polygon
  37876. */
  37877. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37878. var faceUV = fUV || new Array(3);
  37879. var faceColors = fColors;
  37880. var colors = [];
  37881. // default face colors and UV if undefined
  37882. for (var f = 0; f < 3; f++) {
  37883. if (faceUV[f] === undefined) {
  37884. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37885. }
  37886. if (faceColors && faceColors[f] === undefined) {
  37887. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37888. }
  37889. }
  37890. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37891. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37892. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37893. var indices = polygon.getIndices();
  37894. // set face colours and textures
  37895. var idx = 0;
  37896. var face = 0;
  37897. for (var index = 0; index < normals.length; index += 3) {
  37898. //Edge Face no. 1
  37899. if (Math.abs(normals[index + 1]) < 0.001) {
  37900. face = 1;
  37901. }
  37902. //Top Face no. 0
  37903. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37904. face = 0;
  37905. }
  37906. //Bottom Face no. 2
  37907. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37908. face = 2;
  37909. }
  37910. idx = index / 3;
  37911. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37912. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37913. if (faceColors) {
  37914. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37915. }
  37916. }
  37917. // sides
  37918. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37919. // Result
  37920. var vertexData = new VertexData();
  37921. vertexData.indices = indices;
  37922. vertexData.positions = positions;
  37923. vertexData.normals = normals;
  37924. vertexData.uvs = uvs;
  37925. if (faceColors) {
  37926. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37927. vertexData.colors = totalColors;
  37928. }
  37929. return vertexData;
  37930. };
  37931. /**
  37932. * Creates the VertexData of the IcoSphere
  37933. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37934. * * radius the radius of the IcoSphere, optional default 1
  37935. * * radiusX allows stretching in the x direction, optional, default radius
  37936. * * radiusY allows stretching in the y direction, optional, default radius
  37937. * * radiusZ allows stretching in the z direction, optional, default radius
  37938. * * flat when true creates a flat shaded mesh, optional, default true
  37939. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37940. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37941. * * 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)
  37942. * * 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)
  37943. * @returns the VertexData of the IcoSphere
  37944. */
  37945. VertexData.CreateIcoSphere = function (options) {
  37946. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37947. var radius = options.radius || 1;
  37948. var flat = (options.flat === undefined) ? true : options.flat;
  37949. var subdivisions = options.subdivisions || 4;
  37950. var radiusX = options.radiusX || radius;
  37951. var radiusY = options.radiusY || radius;
  37952. var radiusZ = options.radiusZ || radius;
  37953. var t = (1 + Math.sqrt(5)) / 2;
  37954. // 12 vertex x,y,z
  37955. var ico_vertices = [
  37956. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37957. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37958. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37959. ];
  37960. // index of 3 vertex makes a face of icopshere
  37961. var ico_indices = [
  37962. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37963. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37964. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37965. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37966. ];
  37967. // vertex for uv have aliased position, not for UV
  37968. var vertices_unalias_id = [
  37969. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37970. // vertex alias
  37971. 0,
  37972. 2,
  37973. 3,
  37974. 3,
  37975. 3,
  37976. 4,
  37977. 7,
  37978. 8,
  37979. 9,
  37980. 9,
  37981. 10,
  37982. 11 // 23: B + 12
  37983. ];
  37984. // uv as integer step (not pixels !)
  37985. var ico_vertexuv = [
  37986. 5, 1, 3, 1, 6, 4, 0, 0,
  37987. 5, 3, 4, 2, 2, 2, 4, 0,
  37988. 2, 0, 1, 1, 6, 0, 6, 2,
  37989. // vertex alias (for same vertex on different faces)
  37990. 0, 4,
  37991. 3, 3,
  37992. 4, 4,
  37993. 3, 1,
  37994. 4, 2,
  37995. 4, 4,
  37996. 0, 2,
  37997. 1, 1,
  37998. 2, 2,
  37999. 3, 3,
  38000. 1, 3,
  38001. 2, 4 // 23: B + 12
  38002. ];
  38003. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38004. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38005. // First island of uv mapping
  38006. // v = 4h 3+ 2
  38007. // v = 3h 9+ 4
  38008. // v = 2h 9+ 5 B
  38009. // v = 1h 9 1 0
  38010. // v = 0h 3 8 7 A
  38011. // u = 0 1 2 3 4 5 6 *a
  38012. // Second island of uv mapping
  38013. // v = 4h 0+ B+ 4+
  38014. // v = 3h A+ 2+
  38015. // v = 2h 7+ 6 3+
  38016. // v = 1h 8+ 3+
  38017. // v = 0h
  38018. // u = 0 1 2 3 4 5 6 *a
  38019. // Face layout on texture UV mapping
  38020. // ============
  38021. // \ 4 /\ 16 / ======
  38022. // \ / \ / /\ 11 /
  38023. // \/ 7 \/ / \ /
  38024. // ======= / 10 \/
  38025. // /\ 17 /\ =======
  38026. // / \ / \ \ 15 /\
  38027. // / 8 \/ 12 \ \ / \
  38028. // ============ \/ 6 \
  38029. // \ 18 /\ ============
  38030. // \ / \ \ 5 /\ 0 /
  38031. // \/ 13 \ \ / \ /
  38032. // ======= \/ 1 \/
  38033. // =============
  38034. // /\ 19 /\ 2 /\
  38035. // / \ / \ / \
  38036. // / 14 \/ 9 \/ 3 \
  38037. // ===================
  38038. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38039. var ustep = 138 / 1024;
  38040. var vstep = 239 / 1024;
  38041. var uoffset = 60 / 1024;
  38042. var voffset = 26 / 1024;
  38043. // Second island should have margin, not to touch the first island
  38044. // avoid any borderline artefact in pixel rounding
  38045. var island_u_offset = -40 / 1024;
  38046. var island_v_offset = +20 / 1024;
  38047. // face is either island 0 or 1 :
  38048. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38049. var island = [
  38050. 0, 0, 0, 0, 1,
  38051. 0, 0, 1, 1, 0,
  38052. 0, 0, 1, 1, 0,
  38053. 0, 1, 1, 1, 0 // 15 - 19
  38054. ];
  38055. var indices = new Array();
  38056. var positions = new Array();
  38057. var normals = new Array();
  38058. var uvs = new Array();
  38059. var current_indice = 0;
  38060. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38061. var face_vertex_pos = new Array(3);
  38062. var face_vertex_uv = new Array(3);
  38063. var v012;
  38064. for (v012 = 0; v012 < 3; v012++) {
  38065. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38066. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38067. }
  38068. // create all with normals
  38069. for (var face = 0; face < 20; face++) {
  38070. // 3 vertex per face
  38071. for (v012 = 0; v012 < 3; v012++) {
  38072. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38073. var v_id = ico_indices[3 * face + v012];
  38074. // vertex have 3D position (x,y,z)
  38075. 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]);
  38076. // Normalize to get normal, then scale to radius
  38077. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38078. // uv Coordinates from vertex ID
  38079. 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);
  38080. }
  38081. // Subdivide the face (interpolate pos, norm, uv)
  38082. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38083. // - norm is linear interpolation of vertex corner normal
  38084. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38085. // - uv is linear interpolation
  38086. //
  38087. // Topology is as below for sub-divide by 2
  38088. // vertex shown as v0,v1,v2
  38089. // interp index is i1 to progress in range [v0,v1[
  38090. // interp index is i2 to progress in range [v0,v2[
  38091. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38092. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38093. //
  38094. //
  38095. // i2 v2
  38096. // ^ ^
  38097. // / / \
  38098. // / / \
  38099. // / / \
  38100. // / / (0,1) \
  38101. // / #---------\
  38102. // / / \ (0,0)'/ \
  38103. // / / \ / \
  38104. // / / \ / \
  38105. // / / (0,0) \ / (1,0) \
  38106. // / #---------#---------\
  38107. // v0 v1
  38108. //
  38109. // --------------------> i1
  38110. //
  38111. // interp of (i1,i2):
  38112. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38113. // along i1 : lerp(x0,x1, i1/(S-i2))
  38114. //
  38115. // centroid of triangle is needed to get help normal computation
  38116. // (c1,c2) are used for centroid location
  38117. var interp_vertex = function (i1, i2, c1, c2) {
  38118. // vertex is interpolated from
  38119. // - face_vertex_pos[0..2]
  38120. // - face_vertex_uv[0..2]
  38121. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38122. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38123. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38124. pos_interp.normalize();
  38125. var vertex_normal;
  38126. if (flat) {
  38127. // in flat mode, recalculate normal as face centroid normal
  38128. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38129. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38130. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38131. }
  38132. else {
  38133. // in smooth mode, recalculate normal from each single vertex position
  38134. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38135. }
  38136. // Vertex normal need correction due to X,Y,Z radius scaling
  38137. vertex_normal.x /= radiusX;
  38138. vertex_normal.y /= radiusY;
  38139. vertex_normal.z /= radiusZ;
  38140. vertex_normal.normalize();
  38141. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38142. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38143. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38144. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38145. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38146. uvs.push(uv_interp.x, uv_interp.y);
  38147. // push each vertex has member of a face
  38148. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38149. indices.push(current_indice);
  38150. current_indice++;
  38151. };
  38152. for (var i2 = 0; i2 < subdivisions; i2++) {
  38153. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38154. // face : (i1,i2) for /\ :
  38155. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38156. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38157. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38158. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38159. if (i1 + i2 + 1 < subdivisions) {
  38160. // face : (i1,i2)' for \/ :
  38161. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38162. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38163. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38164. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38165. }
  38166. }
  38167. }
  38168. }
  38169. // Sides
  38170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38171. // Result
  38172. var vertexData = new VertexData();
  38173. vertexData.indices = indices;
  38174. vertexData.positions = positions;
  38175. vertexData.normals = normals;
  38176. vertexData.uvs = uvs;
  38177. return vertexData;
  38178. };
  38179. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38180. /**
  38181. * Creates the VertexData for a Polyhedron
  38182. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38183. * * type provided types are:
  38184. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38185. * * 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)
  38186. * * size the size of the IcoSphere, optional default 1
  38187. * * sizeX allows stretching in the x direction, optional, default size
  38188. * * sizeY allows stretching in the y direction, optional, default size
  38189. * * sizeZ allows stretching in the z direction, optional, default size
  38190. * * 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
  38191. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38192. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38193. * * flat when true creates a flat shaded mesh, optional, default true
  38194. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38195. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38196. * * 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)
  38197. * * 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)
  38198. * @returns the VertexData of the Polyhedron
  38199. */
  38200. VertexData.CreatePolyhedron = function (options) {
  38201. // provided polyhedron types :
  38202. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38203. // 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)
  38204. var polyhedra = [];
  38205. 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]] };
  38206. 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]] };
  38207. polyhedra[2] = {
  38208. 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]],
  38209. 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]]
  38210. };
  38211. polyhedra[3] = {
  38212. 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]],
  38213. 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]]
  38214. };
  38215. polyhedra[4] = {
  38216. 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]],
  38217. 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]]
  38218. };
  38219. 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]] };
  38220. 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]] };
  38221. 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]] };
  38222. 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]] };
  38223. 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]] };
  38224. 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]] };
  38225. 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]] };
  38226. 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]] };
  38227. 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]] };
  38228. polyhedra[14] = {
  38229. 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]],
  38230. 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]]
  38231. };
  38232. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38233. var size = options.size;
  38234. var sizeX = options.sizeX || size || 1;
  38235. var sizeY = options.sizeY || size || 1;
  38236. var sizeZ = options.sizeZ || size || 1;
  38237. var data = options.custom || polyhedra[type];
  38238. var nbfaces = data.face.length;
  38239. var faceUV = options.faceUV || new Array(nbfaces);
  38240. var faceColors = options.faceColors;
  38241. var flat = (options.flat === undefined) ? true : options.flat;
  38242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38243. var positions = new Array();
  38244. var indices = new Array();
  38245. var normals = new Array();
  38246. var uvs = new Array();
  38247. var colors = new Array();
  38248. var index = 0;
  38249. var faceIdx = 0; // face cursor in the array "indexes"
  38250. var indexes = new Array();
  38251. var i = 0;
  38252. var f = 0;
  38253. var u, v, ang, x, y, tmp;
  38254. // default face colors and UV if undefined
  38255. if (flat) {
  38256. for (f = 0; f < nbfaces; f++) {
  38257. if (faceColors && faceColors[f] === undefined) {
  38258. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38259. }
  38260. if (faceUV && faceUV[f] === undefined) {
  38261. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38262. }
  38263. }
  38264. }
  38265. if (!flat) {
  38266. for (i = 0; i < data.vertex.length; i++) {
  38267. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38268. uvs.push(0, 0);
  38269. }
  38270. for (f = 0; f < nbfaces; f++) {
  38271. for (i = 0; i < data.face[f].length - 2; i++) {
  38272. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38273. }
  38274. }
  38275. }
  38276. else {
  38277. for (f = 0; f < nbfaces; f++) {
  38278. var fl = data.face[f].length; // number of vertices of the current face
  38279. ang = 2 * Math.PI / fl;
  38280. x = 0.5 * Math.tan(ang / 2);
  38281. y = 0.5;
  38282. // positions, uvs, colors
  38283. for (i = 0; i < fl; i++) {
  38284. // positions
  38285. 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);
  38286. indexes.push(index);
  38287. index++;
  38288. // uvs
  38289. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38290. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38291. uvs.push(u, v);
  38292. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38293. y = x * Math.sin(ang) + y * Math.cos(ang);
  38294. x = tmp;
  38295. // colors
  38296. if (faceColors) {
  38297. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38298. }
  38299. }
  38300. // indices from indexes
  38301. for (i = 0; i < fl - 2; i++) {
  38302. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38303. }
  38304. faceIdx += fl;
  38305. }
  38306. }
  38307. VertexData.ComputeNormals(positions, indices, normals);
  38308. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38309. var vertexData = new VertexData();
  38310. vertexData.positions = positions;
  38311. vertexData.indices = indices;
  38312. vertexData.normals = normals;
  38313. vertexData.uvs = uvs;
  38314. if (faceColors && flat) {
  38315. vertexData.colors = colors;
  38316. }
  38317. return vertexData;
  38318. };
  38319. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38320. /**
  38321. * Creates the VertexData for a TorusKnot
  38322. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38323. * * radius the radius of the torus knot, optional, default 2
  38324. * * tube the thickness of the tube, optional, default 0.5
  38325. * * radialSegments the number of sides on each tube segments, optional, default 32
  38326. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38327. * * p the number of windings around the z axis, optional, default 2
  38328. * * q the number of windings around the x axis, optional, default 3
  38329. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38330. * * 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)
  38331. * * 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)
  38332. * @returns the VertexData of the Torus Knot
  38333. */
  38334. VertexData.CreateTorusKnot = function (options) {
  38335. var indices = new Array();
  38336. var positions = new Array();
  38337. var normals = new Array();
  38338. var uvs = new Array();
  38339. var radius = options.radius || 2;
  38340. var tube = options.tube || 0.5;
  38341. var radialSegments = options.radialSegments || 32;
  38342. var tubularSegments = options.tubularSegments || 32;
  38343. var p = options.p || 2;
  38344. var q = options.q || 3;
  38345. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38346. // Helper
  38347. var getPos = function (angle) {
  38348. var cu = Math.cos(angle);
  38349. var su = Math.sin(angle);
  38350. var quOverP = q / p * angle;
  38351. var cs = Math.cos(quOverP);
  38352. var tx = radius * (2 + cs) * 0.5 * cu;
  38353. var ty = radius * (2 + cs) * su * 0.5;
  38354. var tz = radius * Math.sin(quOverP) * 0.5;
  38355. return new BABYLON.Vector3(tx, ty, tz);
  38356. };
  38357. // Vertices
  38358. var i;
  38359. var j;
  38360. for (i = 0; i <= radialSegments; i++) {
  38361. var modI = i % radialSegments;
  38362. var u = modI / radialSegments * 2 * p * Math.PI;
  38363. var p1 = getPos(u);
  38364. var p2 = getPos(u + 0.01);
  38365. var tang = p2.subtract(p1);
  38366. var n = p2.add(p1);
  38367. var bitan = BABYLON.Vector3.Cross(tang, n);
  38368. n = BABYLON.Vector3.Cross(bitan, tang);
  38369. bitan.normalize();
  38370. n.normalize();
  38371. for (j = 0; j < tubularSegments; j++) {
  38372. var modJ = j % tubularSegments;
  38373. var v = modJ / tubularSegments * 2 * Math.PI;
  38374. var cx = -tube * Math.cos(v);
  38375. var cy = tube * Math.sin(v);
  38376. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38377. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38378. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38379. uvs.push(i / radialSegments);
  38380. uvs.push(j / tubularSegments);
  38381. }
  38382. }
  38383. for (i = 0; i < radialSegments; i++) {
  38384. for (j = 0; j < tubularSegments; j++) {
  38385. var jNext = (j + 1) % tubularSegments;
  38386. var a = i * tubularSegments + j;
  38387. var b = (i + 1) * tubularSegments + j;
  38388. var c = (i + 1) * tubularSegments + jNext;
  38389. var d = i * tubularSegments + jNext;
  38390. indices.push(d);
  38391. indices.push(b);
  38392. indices.push(a);
  38393. indices.push(d);
  38394. indices.push(c);
  38395. indices.push(b);
  38396. }
  38397. }
  38398. // Normals
  38399. VertexData.ComputeNormals(positions, indices, normals);
  38400. // Sides
  38401. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38402. // Result
  38403. var vertexData = new VertexData();
  38404. vertexData.indices = indices;
  38405. vertexData.positions = positions;
  38406. vertexData.normals = normals;
  38407. vertexData.uvs = uvs;
  38408. return vertexData;
  38409. };
  38410. // Tools
  38411. /**
  38412. * Compute normals for given positions and indices
  38413. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38414. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38415. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38416. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38417. * * facetNormals : optional array of facet normals (vector3)
  38418. * * facetPositions : optional array of facet positions (vector3)
  38419. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38420. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38421. * * bInfo : optional bounding info, required for facetPartitioning computation
  38422. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38423. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38424. * * useRightHandedSystem: optional boolean to for right handed system computation
  38425. * * depthSort : optional boolean to enable the facet depth sort computation
  38426. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38427. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38428. */
  38429. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38430. // temporary scalar variables
  38431. var index = 0; // facet index
  38432. var p1p2x = 0.0; // p1p2 vector x coordinate
  38433. var p1p2y = 0.0; // p1p2 vector y coordinate
  38434. var p1p2z = 0.0; // p1p2 vector z coordinate
  38435. var p3p2x = 0.0; // p3p2 vector x coordinate
  38436. var p3p2y = 0.0; // p3p2 vector y coordinate
  38437. var p3p2z = 0.0; // p3p2 vector z coordinate
  38438. var faceNormalx = 0.0; // facet normal x coordinate
  38439. var faceNormaly = 0.0; // facet normal y coordinate
  38440. var faceNormalz = 0.0; // facet normal z coordinate
  38441. var length = 0.0; // facet normal length before normalization
  38442. var v1x = 0; // vector1 x index in the positions array
  38443. var v1y = 0; // vector1 y index in the positions array
  38444. var v1z = 0; // vector1 z index in the positions array
  38445. var v2x = 0; // vector2 x index in the positions array
  38446. var v2y = 0; // vector2 y index in the positions array
  38447. var v2z = 0; // vector2 z index in the positions array
  38448. var v3x = 0; // vector3 x index in the positions array
  38449. var v3y = 0; // vector3 y index in the positions array
  38450. var v3z = 0; // vector3 z index in the positions array
  38451. var computeFacetNormals = false;
  38452. var computeFacetPositions = false;
  38453. var computeFacetPartitioning = false;
  38454. var computeDepthSort = false;
  38455. var faceNormalSign = 1;
  38456. var ratio = 0;
  38457. var distanceTo = null;
  38458. if (options) {
  38459. computeFacetNormals = (options.facetNormals) ? true : false;
  38460. computeFacetPositions = (options.facetPositions) ? true : false;
  38461. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38462. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38463. ratio = options.ratio || 0;
  38464. computeDepthSort = (options.depthSort) ? true : false;
  38465. distanceTo = (options.distanceTo);
  38466. if (computeDepthSort) {
  38467. if (distanceTo === undefined) {
  38468. distanceTo = BABYLON.Vector3.Zero();
  38469. }
  38470. var depthSortedFacets = options.depthSortedFacets;
  38471. }
  38472. }
  38473. // facetPartitioning reinit if needed
  38474. var xSubRatio = 0;
  38475. var ySubRatio = 0;
  38476. var zSubRatio = 0;
  38477. var subSq = 0;
  38478. if (computeFacetPartitioning && options && options.bbSize) {
  38479. var ox = 0; // X partitioning index for facet position
  38480. var oy = 0; // Y partinioning index for facet position
  38481. var oz = 0; // Z partinioning index for facet position
  38482. var b1x = 0; // X partitioning index for facet v1 vertex
  38483. var b1y = 0; // Y partitioning index for facet v1 vertex
  38484. var b1z = 0; // z partitioning index for facet v1 vertex
  38485. var b2x = 0; // X partitioning index for facet v2 vertex
  38486. var b2y = 0; // Y partitioning index for facet v2 vertex
  38487. var b2z = 0; // Z partitioning index for facet v2 vertex
  38488. var b3x = 0; // X partitioning index for facet v3 vertex
  38489. var b3y = 0; // Y partitioning index for facet v3 vertex
  38490. var b3z = 0; // Z partitioning index for facet v3 vertex
  38491. var block_idx_o = 0; // facet barycenter block index
  38492. var block_idx_v1 = 0; // v1 vertex block index
  38493. var block_idx_v2 = 0; // v2 vertex block index
  38494. var block_idx_v3 = 0; // v3 vertex block index
  38495. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38496. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38497. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38498. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38499. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38500. subSq = options.subDiv.max * options.subDiv.max;
  38501. options.facetPartitioning.length = 0;
  38502. }
  38503. // reset the normals
  38504. for (index = 0; index < positions.length; index++) {
  38505. normals[index] = 0.0;
  38506. }
  38507. // Loop : 1 indice triplet = 1 facet
  38508. var nbFaces = (indices.length / 3) | 0;
  38509. for (index = 0; index < nbFaces; index++) {
  38510. // get the indexes of the coordinates of each vertex of the facet
  38511. v1x = indices[index * 3] * 3;
  38512. v1y = v1x + 1;
  38513. v1z = v1x + 2;
  38514. v2x = indices[index * 3 + 1] * 3;
  38515. v2y = v2x + 1;
  38516. v2z = v2x + 2;
  38517. v3x = indices[index * 3 + 2] * 3;
  38518. v3y = v3x + 1;
  38519. v3z = v3x + 2;
  38520. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38521. p1p2y = positions[v1y] - positions[v2y];
  38522. p1p2z = positions[v1z] - positions[v2z];
  38523. p3p2x = positions[v3x] - positions[v2x];
  38524. p3p2y = positions[v3y] - positions[v2y];
  38525. p3p2z = positions[v3z] - positions[v2z];
  38526. // compute the face normal with the cross product
  38527. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38528. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38529. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38530. // normalize this normal and store it in the array facetData
  38531. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38532. length = (length === 0) ? 1.0 : length;
  38533. faceNormalx /= length;
  38534. faceNormaly /= length;
  38535. faceNormalz /= length;
  38536. if (computeFacetNormals && options) {
  38537. options.facetNormals[index].x = faceNormalx;
  38538. options.facetNormals[index].y = faceNormaly;
  38539. options.facetNormals[index].z = faceNormalz;
  38540. }
  38541. if (computeFacetPositions && options) {
  38542. // compute and the facet barycenter coordinates in the array facetPositions
  38543. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38544. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38545. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38546. }
  38547. if (computeFacetPartitioning && options) {
  38548. // store the facet indexes in arrays in the main facetPartitioning array :
  38549. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38550. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38551. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38552. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38553. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38554. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38555. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38556. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38557. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38558. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38559. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38560. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38561. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38562. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38563. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38564. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38565. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38566. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38567. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38568. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38569. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38570. // push each facet index in each block containing the vertex
  38571. options.facetPartitioning[block_idx_v1].push(index);
  38572. if (block_idx_v2 != block_idx_v1) {
  38573. options.facetPartitioning[block_idx_v2].push(index);
  38574. }
  38575. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38576. options.facetPartitioning[block_idx_v3].push(index);
  38577. }
  38578. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38579. options.facetPartitioning[block_idx_o].push(index);
  38580. }
  38581. }
  38582. if (computeDepthSort && options && options.facetPositions) {
  38583. var dsf = depthSortedFacets[index];
  38584. dsf.ind = index * 3;
  38585. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38586. }
  38587. // compute the normals anyway
  38588. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38589. normals[v1y] += faceNormaly;
  38590. normals[v1z] += faceNormalz;
  38591. normals[v2x] += faceNormalx;
  38592. normals[v2y] += faceNormaly;
  38593. normals[v2z] += faceNormalz;
  38594. normals[v3x] += faceNormalx;
  38595. normals[v3y] += faceNormaly;
  38596. normals[v3z] += faceNormalz;
  38597. }
  38598. // last normalization of each normal
  38599. for (index = 0; index < normals.length / 3; index++) {
  38600. faceNormalx = normals[index * 3];
  38601. faceNormaly = normals[index * 3 + 1];
  38602. faceNormalz = normals[index * 3 + 2];
  38603. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38604. length = (length === 0) ? 1.0 : length;
  38605. faceNormalx /= length;
  38606. faceNormaly /= length;
  38607. faceNormalz /= length;
  38608. normals[index * 3] = faceNormalx;
  38609. normals[index * 3 + 1] = faceNormaly;
  38610. normals[index * 3 + 2] = faceNormalz;
  38611. }
  38612. };
  38613. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38614. var li = indices.length;
  38615. var ln = normals.length;
  38616. var i;
  38617. var n;
  38618. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38619. switch (sideOrientation) {
  38620. case BABYLON.Mesh.FRONTSIDE:
  38621. // nothing changed
  38622. break;
  38623. case BABYLON.Mesh.BACKSIDE:
  38624. var tmp;
  38625. // indices
  38626. for (i = 0; i < li; i += 3) {
  38627. tmp = indices[i];
  38628. indices[i] = indices[i + 2];
  38629. indices[i + 2] = tmp;
  38630. }
  38631. // normals
  38632. for (n = 0; n < ln; n++) {
  38633. normals[n] = -normals[n];
  38634. }
  38635. break;
  38636. case BABYLON.Mesh.DOUBLESIDE:
  38637. // positions
  38638. var lp = positions.length;
  38639. var l = lp / 3;
  38640. for (var p = 0; p < lp; p++) {
  38641. positions[lp + p] = positions[p];
  38642. }
  38643. // indices
  38644. for (i = 0; i < li; i += 3) {
  38645. indices[i + li] = indices[i + 2] + l;
  38646. indices[i + 1 + li] = indices[i + 1] + l;
  38647. indices[i + 2 + li] = indices[i] + l;
  38648. }
  38649. // normals
  38650. for (n = 0; n < ln; n++) {
  38651. normals[ln + n] = -normals[n];
  38652. }
  38653. // uvs
  38654. var lu = uvs.length;
  38655. var u = 0;
  38656. for (u = 0; u < lu; u++) {
  38657. uvs[u + lu] = uvs[u];
  38658. }
  38659. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38660. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38661. u = 0;
  38662. for (i = 0; i < lu / 2; i++) {
  38663. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38664. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38665. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38666. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38667. u += 2;
  38668. }
  38669. break;
  38670. }
  38671. };
  38672. /**
  38673. * Applies VertexData created from the imported parameters to the geometry
  38674. * @param parsedVertexData the parsed data from an imported file
  38675. * @param geometry the geometry to apply the VertexData to
  38676. */
  38677. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38678. var vertexData = new VertexData();
  38679. // positions
  38680. var positions = parsedVertexData.positions;
  38681. if (positions) {
  38682. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38683. }
  38684. // normals
  38685. var normals = parsedVertexData.normals;
  38686. if (normals) {
  38687. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38688. }
  38689. // tangents
  38690. var tangents = parsedVertexData.tangents;
  38691. if (tangents) {
  38692. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38693. }
  38694. // uvs
  38695. var uvs = parsedVertexData.uvs;
  38696. if (uvs) {
  38697. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38698. }
  38699. // uv2s
  38700. var uv2s = parsedVertexData.uv2s;
  38701. if (uv2s) {
  38702. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38703. }
  38704. // uv3s
  38705. var uv3s = parsedVertexData.uv3s;
  38706. if (uv3s) {
  38707. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38708. }
  38709. // uv4s
  38710. var uv4s = parsedVertexData.uv4s;
  38711. if (uv4s) {
  38712. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38713. }
  38714. // uv5s
  38715. var uv5s = parsedVertexData.uv5s;
  38716. if (uv5s) {
  38717. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38718. }
  38719. // uv6s
  38720. var uv6s = parsedVertexData.uv6s;
  38721. if (uv6s) {
  38722. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38723. }
  38724. // colors
  38725. var colors = parsedVertexData.colors;
  38726. if (colors) {
  38727. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38728. }
  38729. // matricesIndices
  38730. var matricesIndices = parsedVertexData.matricesIndices;
  38731. if (matricesIndices) {
  38732. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38733. }
  38734. // matricesWeights
  38735. var matricesWeights = parsedVertexData.matricesWeights;
  38736. if (matricesWeights) {
  38737. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38738. }
  38739. // indices
  38740. var indices = parsedVertexData.indices;
  38741. if (indices) {
  38742. vertexData.indices = indices;
  38743. }
  38744. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38745. };
  38746. return VertexData;
  38747. }());
  38748. BABYLON.VertexData = VertexData;
  38749. })(BABYLON || (BABYLON = {}));
  38750. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38751. var BABYLON;
  38752. (function (BABYLON) {
  38753. /**
  38754. * Class used to store geometry data (vertex buffers + index buffer)
  38755. */
  38756. var Geometry = /** @class */ (function () {
  38757. /**
  38758. * Creates a new geometry
  38759. * @param id defines the unique ID
  38760. * @param scene defines the hosting scene
  38761. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38762. * @param updatable defines if geometry must be updatable (false by default)
  38763. * @param mesh defines the mesh that will be associated with the geometry
  38764. */
  38765. function Geometry(id, scene, vertexData, updatable, mesh) {
  38766. if (updatable === void 0) { updatable = false; }
  38767. if (mesh === void 0) { mesh = null; }
  38768. /**
  38769. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38770. */
  38771. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38772. this._totalVertices = 0;
  38773. this._isDisposed = false;
  38774. this._indexBufferIsUpdatable = false;
  38775. this.id = id;
  38776. this._engine = scene.getEngine();
  38777. this._meshes = [];
  38778. this._scene = scene;
  38779. //Init vertex buffer cache
  38780. this._vertexBuffers = {};
  38781. this._indices = [];
  38782. this._updatable = updatable;
  38783. // vertexData
  38784. if (vertexData) {
  38785. this.setAllVerticesData(vertexData, updatable);
  38786. }
  38787. else {
  38788. this._totalVertices = 0;
  38789. this._indices = [];
  38790. }
  38791. if (this._engine.getCaps().vertexArrayObject) {
  38792. this._vertexArrayObjects = {};
  38793. }
  38794. // applyToMesh
  38795. if (mesh) {
  38796. if (mesh.getClassName() === "LinesMesh") {
  38797. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38798. this._updateExtend();
  38799. }
  38800. this.applyToMesh(mesh);
  38801. mesh.computeWorldMatrix(true);
  38802. }
  38803. }
  38804. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38805. /**
  38806. * 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
  38807. */
  38808. get: function () {
  38809. return this._boundingBias;
  38810. },
  38811. /**
  38812. * 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
  38813. */
  38814. set: function (value) {
  38815. if (this._boundingBias && this._boundingBias.equals(value)) {
  38816. return;
  38817. }
  38818. this._boundingBias = value.clone();
  38819. this._updateBoundingInfo(true, null);
  38820. },
  38821. enumerable: true,
  38822. configurable: true
  38823. });
  38824. /**
  38825. * Static function used to attach a new empty geometry to a mesh
  38826. * @param mesh defines the mesh to attach the geometry to
  38827. * @returns the new {BABYLON.Geometry}
  38828. */
  38829. Geometry.CreateGeometryForMesh = function (mesh) {
  38830. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38831. geometry.applyToMesh(mesh);
  38832. return geometry;
  38833. };
  38834. Object.defineProperty(Geometry.prototype, "extend", {
  38835. /**
  38836. * Gets the current extend of the geometry
  38837. */
  38838. get: function () {
  38839. return this._extend;
  38840. },
  38841. enumerable: true,
  38842. configurable: true
  38843. });
  38844. /**
  38845. * Gets the hosting scene
  38846. * @returns the hosting {BABYLON.Scene}
  38847. */
  38848. Geometry.prototype.getScene = function () {
  38849. return this._scene;
  38850. };
  38851. /**
  38852. * Gets the hosting engine
  38853. * @returns the hosting {BABYLON.Engine}
  38854. */
  38855. Geometry.prototype.getEngine = function () {
  38856. return this._engine;
  38857. };
  38858. /**
  38859. * Defines if the geometry is ready to use
  38860. * @returns true if the geometry is ready to be used
  38861. */
  38862. Geometry.prototype.isReady = function () {
  38863. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38864. };
  38865. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38866. /**
  38867. * Gets a value indicating that the geometry should not be serialized
  38868. */
  38869. get: function () {
  38870. for (var index = 0; index < this._meshes.length; index++) {
  38871. if (!this._meshes[index].doNotSerialize) {
  38872. return false;
  38873. }
  38874. }
  38875. return true;
  38876. },
  38877. enumerable: true,
  38878. configurable: true
  38879. });
  38880. /** @hidden */
  38881. Geometry.prototype._rebuild = function () {
  38882. if (this._vertexArrayObjects) {
  38883. this._vertexArrayObjects = {};
  38884. }
  38885. // Index buffer
  38886. if (this._meshes.length !== 0 && this._indices) {
  38887. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38888. }
  38889. // Vertex buffers
  38890. for (var key in this._vertexBuffers) {
  38891. var vertexBuffer = this._vertexBuffers[key];
  38892. vertexBuffer._rebuild();
  38893. }
  38894. };
  38895. /**
  38896. * Affects all geometry data in one call
  38897. * @param vertexData defines the geometry data
  38898. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38899. */
  38900. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38901. vertexData.applyToGeometry(this, updatable);
  38902. this.notifyUpdate();
  38903. };
  38904. /**
  38905. * Set specific vertex data
  38906. * @param kind defines the data kind (Position, normal, etc...)
  38907. * @param data defines the vertex data to use
  38908. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38909. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38910. */
  38911. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38912. if (updatable === void 0) { updatable = false; }
  38913. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38914. this.setVerticesBuffer(buffer);
  38915. };
  38916. /**
  38917. * Removes a specific vertex data
  38918. * @param kind defines the data kind (Position, normal, etc...)
  38919. */
  38920. Geometry.prototype.removeVerticesData = function (kind) {
  38921. if (this._vertexBuffers[kind]) {
  38922. this._vertexBuffers[kind].dispose();
  38923. delete this._vertexBuffers[kind];
  38924. }
  38925. };
  38926. /**
  38927. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38928. * @param buffer defines the vertex buffer to use
  38929. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38930. */
  38931. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38932. if (totalVertices === void 0) { totalVertices = null; }
  38933. var kind = buffer.getKind();
  38934. if (this._vertexBuffers[kind]) {
  38935. this._vertexBuffers[kind].dispose();
  38936. }
  38937. this._vertexBuffers[kind] = buffer;
  38938. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38939. var data = buffer.getData();
  38940. if (totalVertices != null) {
  38941. this._totalVertices = totalVertices;
  38942. }
  38943. else {
  38944. if (data != null) {
  38945. this._totalVertices = data.length / (buffer.byteStride / 4);
  38946. }
  38947. }
  38948. this._updateExtend(data);
  38949. this._resetPointsArrayCache();
  38950. var meshes = this._meshes;
  38951. var numOfMeshes = meshes.length;
  38952. for (var index = 0; index < numOfMeshes; index++) {
  38953. var mesh = meshes[index];
  38954. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38955. mesh._createGlobalSubMesh(false);
  38956. mesh.computeWorldMatrix(true);
  38957. }
  38958. }
  38959. this.notifyUpdate(kind);
  38960. if (this._vertexArrayObjects) {
  38961. this._disposeVertexArrayObjects();
  38962. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38963. }
  38964. };
  38965. /**
  38966. * Update a specific vertex buffer
  38967. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38968. * It will do nothing if the buffer is not updatable
  38969. * @param kind defines the data kind (Position, normal, etc...)
  38970. * @param data defines the data to use
  38971. * @param offset defines the offset in the target buffer where to store the data
  38972. * @param useBytes set to true if the offset is in bytes
  38973. */
  38974. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38975. if (useBytes === void 0) { useBytes = false; }
  38976. var vertexBuffer = this.getVertexBuffer(kind);
  38977. if (!vertexBuffer) {
  38978. return;
  38979. }
  38980. vertexBuffer.updateDirectly(data, offset, useBytes);
  38981. this.notifyUpdate(kind);
  38982. };
  38983. /**
  38984. * Update a specific vertex buffer
  38985. * This function will create a new buffer if the current one is not updatable
  38986. * @param kind defines the data kind (Position, normal, etc...)
  38987. * @param data defines the data to use
  38988. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38989. */
  38990. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38991. if (updateExtends === void 0) { updateExtends = false; }
  38992. var vertexBuffer = this.getVertexBuffer(kind);
  38993. if (!vertexBuffer) {
  38994. return;
  38995. }
  38996. vertexBuffer.update(data);
  38997. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38998. this._updateBoundingInfo(updateExtends, data);
  38999. }
  39000. this.notifyUpdate(kind);
  39001. };
  39002. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39003. if (updateExtends) {
  39004. this._updateExtend(data);
  39005. }
  39006. var meshes = this._meshes;
  39007. var numOfMeshes = meshes.length;
  39008. this._resetPointsArrayCache();
  39009. for (var index = 0; index < numOfMeshes; index++) {
  39010. var mesh = meshes[index];
  39011. if (updateExtends) {
  39012. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39013. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39014. var subMesh = mesh.subMeshes[subIndex];
  39015. subMesh.refreshBoundingInfo();
  39016. }
  39017. }
  39018. }
  39019. };
  39020. /** @hidden */
  39021. Geometry.prototype._bind = function (effect, indexToBind) {
  39022. if (!effect) {
  39023. return;
  39024. }
  39025. if (indexToBind === undefined) {
  39026. indexToBind = this._indexBuffer;
  39027. }
  39028. var vbs = this.getVertexBuffers();
  39029. if (!vbs) {
  39030. return;
  39031. }
  39032. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39033. this._engine.bindBuffers(vbs, indexToBind, effect);
  39034. return;
  39035. }
  39036. // Using VAO
  39037. if (!this._vertexArrayObjects[effect.key]) {
  39038. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39039. }
  39040. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39041. };
  39042. /**
  39043. * Gets total number of vertices
  39044. * @returns the total number of vertices
  39045. */
  39046. Geometry.prototype.getTotalVertices = function () {
  39047. if (!this.isReady()) {
  39048. return 0;
  39049. }
  39050. return this._totalVertices;
  39051. };
  39052. /**
  39053. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39054. * @param kind defines the data kind (Position, normal, etc...)
  39055. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39056. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39057. * @returns a float array containing vertex data
  39058. */
  39059. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39060. var vertexBuffer = this.getVertexBuffer(kind);
  39061. if (!vertexBuffer) {
  39062. return null;
  39063. }
  39064. var data = vertexBuffer.getData();
  39065. if (!data) {
  39066. return null;
  39067. }
  39068. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39069. var count = this._totalVertices * vertexBuffer.getSize();
  39070. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39071. var copy_1 = new Array(count);
  39072. vertexBuffer.forEach(count, function (value, index) {
  39073. copy_1[index] = value;
  39074. });
  39075. return copy_1;
  39076. }
  39077. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39078. if (data instanceof Array) {
  39079. var offset = vertexBuffer.byteOffset / 4;
  39080. return BABYLON.Tools.Slice(data, offset, offset + count);
  39081. }
  39082. else if (data instanceof ArrayBuffer) {
  39083. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39084. }
  39085. else {
  39086. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39087. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39088. var result = new Float32Array(count);
  39089. var source = new Float32Array(data.buffer, offset, count);
  39090. result.set(source);
  39091. return result;
  39092. }
  39093. return new Float32Array(data.buffer, offset, count);
  39094. }
  39095. }
  39096. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39097. return BABYLON.Tools.Slice(data);
  39098. }
  39099. return data;
  39100. };
  39101. /**
  39102. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39103. * @param kind defines the data kind (Position, normal, etc...)
  39104. * @returns true if the vertex buffer with the specified kind is updatable
  39105. */
  39106. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39107. var vb = this._vertexBuffers[kind];
  39108. if (!vb) {
  39109. return false;
  39110. }
  39111. return vb.isUpdatable();
  39112. };
  39113. /**
  39114. * Gets a specific vertex buffer
  39115. * @param kind defines the data kind (Position, normal, etc...)
  39116. * @returns a {BABYLON.VertexBuffer}
  39117. */
  39118. Geometry.prototype.getVertexBuffer = function (kind) {
  39119. if (!this.isReady()) {
  39120. return null;
  39121. }
  39122. return this._vertexBuffers[kind];
  39123. };
  39124. /**
  39125. * Returns all vertex buffers
  39126. * @return an object holding all vertex buffers indexed by kind
  39127. */
  39128. Geometry.prototype.getVertexBuffers = function () {
  39129. if (!this.isReady()) {
  39130. return null;
  39131. }
  39132. return this._vertexBuffers;
  39133. };
  39134. /**
  39135. * Gets a boolean indicating if specific vertex buffer is present
  39136. * @param kind defines the data kind (Position, normal, etc...)
  39137. * @returns true if data is present
  39138. */
  39139. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39140. if (!this._vertexBuffers) {
  39141. if (this._delayInfo) {
  39142. return this._delayInfo.indexOf(kind) !== -1;
  39143. }
  39144. return false;
  39145. }
  39146. return this._vertexBuffers[kind] !== undefined;
  39147. };
  39148. /**
  39149. * Gets a list of all attached data kinds (Position, normal, etc...)
  39150. * @returns a list of string containing all kinds
  39151. */
  39152. Geometry.prototype.getVerticesDataKinds = function () {
  39153. var result = [];
  39154. var kind;
  39155. if (!this._vertexBuffers && this._delayInfo) {
  39156. for (kind in this._delayInfo) {
  39157. result.push(kind);
  39158. }
  39159. }
  39160. else {
  39161. for (kind in this._vertexBuffers) {
  39162. result.push(kind);
  39163. }
  39164. }
  39165. return result;
  39166. };
  39167. /**
  39168. * Update index buffer
  39169. * @param indices defines the indices to store in the index buffer
  39170. * @param offset defines the offset in the target buffer where to store the data
  39171. */
  39172. Geometry.prototype.updateIndices = function (indices, offset) {
  39173. if (!this._indexBuffer) {
  39174. return;
  39175. }
  39176. if (!this._indexBufferIsUpdatable) {
  39177. this.setIndices(indices, null, true);
  39178. }
  39179. else {
  39180. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39181. }
  39182. };
  39183. /**
  39184. * Creates a new index buffer
  39185. * @param indices defines the indices to store in the index buffer
  39186. * @param totalVertices defines the total number of vertices (could be null)
  39187. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39188. */
  39189. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39190. if (totalVertices === void 0) { totalVertices = null; }
  39191. if (updatable === void 0) { updatable = false; }
  39192. if (this._indexBuffer) {
  39193. this._engine._releaseBuffer(this._indexBuffer);
  39194. }
  39195. this._disposeVertexArrayObjects();
  39196. this._indices = indices;
  39197. this._indexBufferIsUpdatable = updatable;
  39198. if (this._meshes.length !== 0 && this._indices) {
  39199. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39200. }
  39201. if (totalVertices != undefined) { // including null and undefined
  39202. this._totalVertices = totalVertices;
  39203. }
  39204. var meshes = this._meshes;
  39205. var numOfMeshes = meshes.length;
  39206. for (var index = 0; index < numOfMeshes; index++) {
  39207. meshes[index]._createGlobalSubMesh(true);
  39208. }
  39209. this.notifyUpdate();
  39210. };
  39211. /**
  39212. * Return the total number of indices
  39213. * @returns the total number of indices
  39214. */
  39215. Geometry.prototype.getTotalIndices = function () {
  39216. if (!this.isReady()) {
  39217. return 0;
  39218. }
  39219. return this._indices.length;
  39220. };
  39221. /**
  39222. * Gets the index buffer array
  39223. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39224. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39225. * @returns the index buffer array
  39226. */
  39227. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39228. if (!this.isReady()) {
  39229. return null;
  39230. }
  39231. var orig = this._indices;
  39232. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39233. return orig;
  39234. }
  39235. else {
  39236. var len = orig.length;
  39237. var copy = [];
  39238. for (var i = 0; i < len; i++) {
  39239. copy.push(orig[i]);
  39240. }
  39241. return copy;
  39242. }
  39243. };
  39244. /**
  39245. * Gets the index buffer
  39246. * @return the index buffer
  39247. */
  39248. Geometry.prototype.getIndexBuffer = function () {
  39249. if (!this.isReady()) {
  39250. return null;
  39251. }
  39252. return this._indexBuffer;
  39253. };
  39254. /** @hidden */
  39255. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39256. if (effect === void 0) { effect = null; }
  39257. if (!effect || !this._vertexArrayObjects) {
  39258. return;
  39259. }
  39260. if (this._vertexArrayObjects[effect.key]) {
  39261. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39262. delete this._vertexArrayObjects[effect.key];
  39263. }
  39264. };
  39265. /**
  39266. * Release the associated resources for a specific mesh
  39267. * @param mesh defines the source mesh
  39268. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39269. */
  39270. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39271. var meshes = this._meshes;
  39272. var index = meshes.indexOf(mesh);
  39273. if (index === -1) {
  39274. return;
  39275. }
  39276. meshes.splice(index, 1);
  39277. mesh._geometry = null;
  39278. if (meshes.length === 0 && shouldDispose) {
  39279. this.dispose();
  39280. }
  39281. };
  39282. /**
  39283. * Apply current geometry to a given mesh
  39284. * @param mesh defines the mesh to apply geometry to
  39285. */
  39286. Geometry.prototype.applyToMesh = function (mesh) {
  39287. if (mesh._geometry === this) {
  39288. return;
  39289. }
  39290. var previousGeometry = mesh._geometry;
  39291. if (previousGeometry) {
  39292. previousGeometry.releaseForMesh(mesh);
  39293. }
  39294. var meshes = this._meshes;
  39295. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39296. mesh._geometry = this;
  39297. this._scene.pushGeometry(this);
  39298. meshes.push(mesh);
  39299. if (this.isReady()) {
  39300. this._applyToMesh(mesh);
  39301. }
  39302. else {
  39303. mesh._boundingInfo = this._boundingInfo;
  39304. }
  39305. };
  39306. Geometry.prototype._updateExtend = function (data) {
  39307. if (data === void 0) { data = null; }
  39308. if (!data) {
  39309. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39310. }
  39311. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39312. };
  39313. Geometry.prototype._applyToMesh = function (mesh) {
  39314. var numOfMeshes = this._meshes.length;
  39315. // vertexBuffers
  39316. for (var kind in this._vertexBuffers) {
  39317. if (numOfMeshes === 1) {
  39318. this._vertexBuffers[kind].create();
  39319. }
  39320. var buffer = this._vertexBuffers[kind].getBuffer();
  39321. if (buffer)
  39322. buffer.references = numOfMeshes;
  39323. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39324. if (!this._extend) {
  39325. this._updateExtend();
  39326. }
  39327. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39328. mesh._createGlobalSubMesh(false);
  39329. //bounding info was just created again, world matrix should be applied again.
  39330. mesh._updateBoundingInfo();
  39331. }
  39332. }
  39333. // indexBuffer
  39334. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39335. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39336. }
  39337. if (this._indexBuffer) {
  39338. this._indexBuffer.references = numOfMeshes;
  39339. }
  39340. };
  39341. Geometry.prototype.notifyUpdate = function (kind) {
  39342. if (this.onGeometryUpdated) {
  39343. this.onGeometryUpdated(this, kind);
  39344. }
  39345. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39346. var mesh = _a[_i];
  39347. mesh._markSubMeshesAsAttributesDirty();
  39348. }
  39349. };
  39350. /**
  39351. * Load the geometry if it was flagged as delay loaded
  39352. * @param scene defines the hosting scene
  39353. * @param onLoaded defines a callback called when the geometry is loaded
  39354. */
  39355. Geometry.prototype.load = function (scene, onLoaded) {
  39356. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39357. return;
  39358. }
  39359. if (this.isReady()) {
  39360. if (onLoaded) {
  39361. onLoaded();
  39362. }
  39363. return;
  39364. }
  39365. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39366. this._queueLoad(scene, onLoaded);
  39367. };
  39368. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39369. var _this = this;
  39370. if (!this.delayLoadingFile) {
  39371. return;
  39372. }
  39373. scene._addPendingData(this);
  39374. scene._loadFile(this.delayLoadingFile, function (data) {
  39375. if (!_this._delayLoadingFunction) {
  39376. return;
  39377. }
  39378. _this._delayLoadingFunction(JSON.parse(data), _this);
  39379. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39380. _this._delayInfo = [];
  39381. scene._removePendingData(_this);
  39382. var meshes = _this._meshes;
  39383. var numOfMeshes = meshes.length;
  39384. for (var index = 0; index < numOfMeshes; index++) {
  39385. _this._applyToMesh(meshes[index]);
  39386. }
  39387. if (onLoaded) {
  39388. onLoaded();
  39389. }
  39390. }, undefined, true);
  39391. };
  39392. /**
  39393. * Invert the geometry to move from a right handed system to a left handed one.
  39394. */
  39395. Geometry.prototype.toLeftHanded = function () {
  39396. // Flip faces
  39397. var tIndices = this.getIndices(false);
  39398. if (tIndices != null && tIndices.length > 0) {
  39399. for (var i = 0; i < tIndices.length; i += 3) {
  39400. var tTemp = tIndices[i + 0];
  39401. tIndices[i + 0] = tIndices[i + 2];
  39402. tIndices[i + 2] = tTemp;
  39403. }
  39404. this.setIndices(tIndices);
  39405. }
  39406. // Negate position.z
  39407. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39408. if (tPositions != null && tPositions.length > 0) {
  39409. for (var i = 0; i < tPositions.length; i += 3) {
  39410. tPositions[i + 2] = -tPositions[i + 2];
  39411. }
  39412. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39413. }
  39414. // Negate normal.z
  39415. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39416. if (tNormals != null && tNormals.length > 0) {
  39417. for (var i = 0; i < tNormals.length; i += 3) {
  39418. tNormals[i + 2] = -tNormals[i + 2];
  39419. }
  39420. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39421. }
  39422. };
  39423. // Cache
  39424. /** @hidden */
  39425. Geometry.prototype._resetPointsArrayCache = function () {
  39426. this._positions = null;
  39427. };
  39428. /** @hidden */
  39429. Geometry.prototype._generatePointsArray = function () {
  39430. if (this._positions)
  39431. return true;
  39432. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39433. if (!data || data.length === 0) {
  39434. return false;
  39435. }
  39436. this._positions = [];
  39437. for (var index = 0; index < data.length; index += 3) {
  39438. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39439. }
  39440. return true;
  39441. };
  39442. /**
  39443. * Gets a value indicating if the geometry is disposed
  39444. * @returns true if the geometry was disposed
  39445. */
  39446. Geometry.prototype.isDisposed = function () {
  39447. return this._isDisposed;
  39448. };
  39449. Geometry.prototype._disposeVertexArrayObjects = function () {
  39450. if (this._vertexArrayObjects) {
  39451. for (var kind in this._vertexArrayObjects) {
  39452. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39453. }
  39454. this._vertexArrayObjects = {};
  39455. }
  39456. };
  39457. /**
  39458. * Free all associated resources
  39459. */
  39460. Geometry.prototype.dispose = function () {
  39461. var meshes = this._meshes;
  39462. var numOfMeshes = meshes.length;
  39463. var index;
  39464. for (index = 0; index < numOfMeshes; index++) {
  39465. this.releaseForMesh(meshes[index]);
  39466. }
  39467. this._meshes = [];
  39468. this._disposeVertexArrayObjects();
  39469. for (var kind in this._vertexBuffers) {
  39470. this._vertexBuffers[kind].dispose();
  39471. }
  39472. this._vertexBuffers = {};
  39473. this._totalVertices = 0;
  39474. if (this._indexBuffer) {
  39475. this._engine._releaseBuffer(this._indexBuffer);
  39476. }
  39477. this._indexBuffer = null;
  39478. this._indices = [];
  39479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39480. this.delayLoadingFile = null;
  39481. this._delayLoadingFunction = null;
  39482. this._delayInfo = [];
  39483. this._boundingInfo = null;
  39484. this._scene.removeGeometry(this);
  39485. this._isDisposed = true;
  39486. };
  39487. /**
  39488. * Clone the current geometry into a new geometry
  39489. * @param id defines the unique ID of the new geometry
  39490. * @returns a new geometry object
  39491. */
  39492. Geometry.prototype.copy = function (id) {
  39493. var vertexData = new BABYLON.VertexData();
  39494. vertexData.indices = [];
  39495. var indices = this.getIndices();
  39496. if (indices) {
  39497. for (var index = 0; index < indices.length; index++) {
  39498. vertexData.indices.push(indices[index]);
  39499. }
  39500. }
  39501. var updatable = false;
  39502. var stopChecking = false;
  39503. var kind;
  39504. for (kind in this._vertexBuffers) {
  39505. // using slice() to make a copy of the array and not just reference it
  39506. var data = this.getVerticesData(kind);
  39507. if (data instanceof Float32Array) {
  39508. vertexData.set(new Float32Array(data), kind);
  39509. }
  39510. else {
  39511. vertexData.set(data.slice(0), kind);
  39512. }
  39513. if (!stopChecking) {
  39514. var vb = this.getVertexBuffer(kind);
  39515. if (vb) {
  39516. updatable = vb.isUpdatable();
  39517. stopChecking = !updatable;
  39518. }
  39519. }
  39520. }
  39521. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39522. geometry.delayLoadState = this.delayLoadState;
  39523. geometry.delayLoadingFile = this.delayLoadingFile;
  39524. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39525. for (kind in this._delayInfo) {
  39526. geometry._delayInfo = geometry._delayInfo || [];
  39527. geometry._delayInfo.push(kind);
  39528. }
  39529. // Bounding info
  39530. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39531. return geometry;
  39532. };
  39533. /**
  39534. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39535. * @return a JSON representation of the current geometry data (without the vertices data)
  39536. */
  39537. Geometry.prototype.serialize = function () {
  39538. var serializationObject = {};
  39539. serializationObject.id = this.id;
  39540. serializationObject.updatable = this._updatable;
  39541. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39542. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39543. }
  39544. return serializationObject;
  39545. };
  39546. Geometry.prototype.toNumberArray = function (origin) {
  39547. if (Array.isArray(origin)) {
  39548. return origin;
  39549. }
  39550. else {
  39551. return Array.prototype.slice.call(origin);
  39552. }
  39553. };
  39554. /**
  39555. * Serialize all vertices data into a JSON oject
  39556. * @returns a JSON representation of the current geometry data
  39557. */
  39558. Geometry.prototype.serializeVerticeData = function () {
  39559. var serializationObject = this.serialize();
  39560. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39561. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39562. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39563. serializationObject.positions._updatable = true;
  39564. }
  39565. }
  39566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39567. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39568. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39569. serializationObject.normals._updatable = true;
  39570. }
  39571. }
  39572. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39573. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39574. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39575. serializationObject.tangets._updatable = true;
  39576. }
  39577. }
  39578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39579. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39580. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39581. serializationObject.uvs._updatable = true;
  39582. }
  39583. }
  39584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39585. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39586. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39587. serializationObject.uv2s._updatable = true;
  39588. }
  39589. }
  39590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39591. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39592. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39593. serializationObject.uv3s._updatable = true;
  39594. }
  39595. }
  39596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39597. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39599. serializationObject.uv4s._updatable = true;
  39600. }
  39601. }
  39602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39603. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39604. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39605. serializationObject.uv5s._updatable = true;
  39606. }
  39607. }
  39608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39609. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39610. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39611. serializationObject.uv6s._updatable = true;
  39612. }
  39613. }
  39614. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39615. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39616. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39617. serializationObject.colors._updatable = true;
  39618. }
  39619. }
  39620. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39621. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39622. serializationObject.matricesIndices._isExpanded = true;
  39623. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39624. serializationObject.matricesIndices._updatable = true;
  39625. }
  39626. }
  39627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39628. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39629. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39630. serializationObject.matricesWeights._updatable = true;
  39631. }
  39632. }
  39633. serializationObject.indices = this.toNumberArray(this.getIndices());
  39634. return serializationObject;
  39635. };
  39636. // Statics
  39637. /**
  39638. * Extracts a clone of a mesh geometry
  39639. * @param mesh defines the source mesh
  39640. * @param id defines the unique ID of the new geometry object
  39641. * @returns the new geometry object
  39642. */
  39643. Geometry.ExtractFromMesh = function (mesh, id) {
  39644. var geometry = mesh._geometry;
  39645. if (!geometry) {
  39646. return null;
  39647. }
  39648. return geometry.copy(id);
  39649. };
  39650. /**
  39651. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39652. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39653. * Be aware Math.random() could cause collisions, but:
  39654. * "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"
  39655. * @returns a string containing a new GUID
  39656. */
  39657. Geometry.RandomId = function () {
  39658. return BABYLON.Tools.RandomId();
  39659. };
  39660. /** @hidden */
  39661. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39662. var scene = mesh.getScene();
  39663. // Geometry
  39664. var geometryId = parsedGeometry.geometryId;
  39665. if (geometryId) {
  39666. var geometry = scene.getGeometryByID(geometryId);
  39667. if (geometry) {
  39668. geometry.applyToMesh(mesh);
  39669. }
  39670. }
  39671. else if (parsedGeometry instanceof ArrayBuffer) {
  39672. var binaryInfo = mesh._binaryInfo;
  39673. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39674. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39675. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39676. }
  39677. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39678. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39679. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39680. }
  39681. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39682. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39683. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39684. }
  39685. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39686. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39687. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39688. }
  39689. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39690. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39691. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39692. }
  39693. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39694. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39695. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39696. }
  39697. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39698. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39699. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39700. }
  39701. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39702. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39703. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39704. }
  39705. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39706. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39707. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39708. }
  39709. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39710. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39711. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39712. }
  39713. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39714. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39715. var floatIndices = [];
  39716. for (var i = 0; i < matricesIndicesData.length; i++) {
  39717. var index = matricesIndicesData[i];
  39718. floatIndices.push(index & 0x000000FF);
  39719. floatIndices.push((index & 0x0000FF00) >> 8);
  39720. floatIndices.push((index & 0x00FF0000) >> 16);
  39721. floatIndices.push(index >> 24);
  39722. }
  39723. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39724. }
  39725. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39726. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39727. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39728. }
  39729. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39730. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39731. mesh.setIndices(indicesData, null);
  39732. }
  39733. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39734. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39735. mesh.subMeshes = [];
  39736. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39737. var materialIndex = subMeshesData[(i * 5) + 0];
  39738. var verticesStart = subMeshesData[(i * 5) + 1];
  39739. var verticesCount = subMeshesData[(i * 5) + 2];
  39740. var indexStart = subMeshesData[(i * 5) + 3];
  39741. var indexCount = subMeshesData[(i * 5) + 4];
  39742. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39743. }
  39744. }
  39745. }
  39746. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39747. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39748. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39749. if (parsedGeometry.tangents) {
  39750. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39751. }
  39752. if (parsedGeometry.uvs) {
  39753. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39754. }
  39755. if (parsedGeometry.uvs2) {
  39756. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39757. }
  39758. if (parsedGeometry.uvs3) {
  39759. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39760. }
  39761. if (parsedGeometry.uvs4) {
  39762. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39763. }
  39764. if (parsedGeometry.uvs5) {
  39765. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39766. }
  39767. if (parsedGeometry.uvs6) {
  39768. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39769. }
  39770. if (parsedGeometry.colors) {
  39771. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39772. }
  39773. if (parsedGeometry.matricesIndices) {
  39774. if (!parsedGeometry.matricesIndices._isExpanded) {
  39775. var floatIndices = [];
  39776. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39777. var matricesIndex = parsedGeometry.matricesIndices[i];
  39778. floatIndices.push(matricesIndex & 0x000000FF);
  39779. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39780. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39781. floatIndices.push(matricesIndex >> 24);
  39782. }
  39783. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39784. }
  39785. else {
  39786. delete parsedGeometry.matricesIndices._isExpanded;
  39787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39788. }
  39789. }
  39790. if (parsedGeometry.matricesIndicesExtra) {
  39791. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39792. var floatIndices = [];
  39793. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39794. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39795. floatIndices.push(matricesIndex & 0x000000FF);
  39796. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39797. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39798. floatIndices.push(matricesIndex >> 24);
  39799. }
  39800. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39801. }
  39802. else {
  39803. delete parsedGeometry.matricesIndices._isExpanded;
  39804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39805. }
  39806. }
  39807. if (parsedGeometry.matricesWeights) {
  39808. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39809. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39810. }
  39811. if (parsedGeometry.matricesWeightsExtra) {
  39812. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39813. }
  39814. mesh.setIndices(parsedGeometry.indices, null);
  39815. }
  39816. // SubMeshes
  39817. if (parsedGeometry.subMeshes) {
  39818. mesh.subMeshes = [];
  39819. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39820. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39821. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39822. }
  39823. }
  39824. // Flat shading
  39825. if (mesh._shouldGenerateFlatShading) {
  39826. mesh.convertToFlatShadedMesh();
  39827. delete mesh._shouldGenerateFlatShading;
  39828. }
  39829. // Update
  39830. mesh.computeWorldMatrix(true);
  39831. scene.onMeshImportedObservable.notifyObservers(mesh);
  39832. };
  39833. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39834. var epsilon = 1e-3;
  39835. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39836. return;
  39837. }
  39838. var noInfluenceBoneIndex = 0.0;
  39839. if (parsedGeometry.skeletonId > -1) {
  39840. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39841. if (!skeleton) {
  39842. return;
  39843. }
  39844. noInfluenceBoneIndex = skeleton.bones.length;
  39845. }
  39846. else {
  39847. return;
  39848. }
  39849. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39850. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39851. var matricesWeights = parsedGeometry.matricesWeights;
  39852. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39853. var influencers = parsedGeometry.numBoneInfluencer;
  39854. var size = matricesWeights.length;
  39855. for (var i = 0; i < size; i += 4) {
  39856. var weight = 0.0;
  39857. var firstZeroWeight = -1;
  39858. for (var j = 0; j < 4; j++) {
  39859. var w = matricesWeights[i + j];
  39860. weight += w;
  39861. if (w < epsilon && firstZeroWeight < 0) {
  39862. firstZeroWeight = j;
  39863. }
  39864. }
  39865. if (matricesWeightsExtra) {
  39866. for (var j = 0; j < 4; j++) {
  39867. var w = matricesWeightsExtra[i + j];
  39868. weight += w;
  39869. if (w < epsilon && firstZeroWeight < 0) {
  39870. firstZeroWeight = j + 4;
  39871. }
  39872. }
  39873. }
  39874. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39875. firstZeroWeight = influencers - 1;
  39876. }
  39877. if (weight > epsilon) {
  39878. var mweight = 1.0 / weight;
  39879. for (var j = 0; j < 4; j++) {
  39880. matricesWeights[i + j] *= mweight;
  39881. }
  39882. if (matricesWeightsExtra) {
  39883. for (var j = 0; j < 4; j++) {
  39884. matricesWeightsExtra[i + j] *= mweight;
  39885. }
  39886. }
  39887. }
  39888. else {
  39889. if (firstZeroWeight >= 4) {
  39890. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39891. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39892. }
  39893. else {
  39894. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39895. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39896. }
  39897. }
  39898. }
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39900. if (parsedGeometry.matricesWeightsExtra) {
  39901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39902. }
  39903. };
  39904. /**
  39905. * Create a new geometry from persisted data (Using .babylon file format)
  39906. * @param parsedVertexData defines the persisted data
  39907. * @param scene defines the hosting scene
  39908. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39909. * @returns the new geometry object
  39910. */
  39911. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39912. if (scene.getGeometryByID(parsedVertexData.id)) {
  39913. return null; // null since geometry could be something else than a box...
  39914. }
  39915. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39916. if (BABYLON.Tags) {
  39917. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39918. }
  39919. if (parsedVertexData.delayLoadingFile) {
  39920. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39921. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39922. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39923. geometry._delayInfo = [];
  39924. if (parsedVertexData.hasUVs) {
  39925. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39926. }
  39927. if (parsedVertexData.hasUVs2) {
  39928. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39929. }
  39930. if (parsedVertexData.hasUVs3) {
  39931. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39932. }
  39933. if (parsedVertexData.hasUVs4) {
  39934. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39935. }
  39936. if (parsedVertexData.hasUVs5) {
  39937. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39938. }
  39939. if (parsedVertexData.hasUVs6) {
  39940. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39941. }
  39942. if (parsedVertexData.hasColors) {
  39943. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39944. }
  39945. if (parsedVertexData.hasMatricesIndices) {
  39946. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39947. }
  39948. if (parsedVertexData.hasMatricesWeights) {
  39949. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39950. }
  39951. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39952. }
  39953. else {
  39954. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39955. }
  39956. scene.pushGeometry(geometry, true);
  39957. return geometry;
  39958. };
  39959. return Geometry;
  39960. }());
  39961. BABYLON.Geometry = Geometry;
  39962. // Primitives
  39963. /// Abstract class
  39964. /**
  39965. * Abstract class used to provide common services for all typed geometries
  39966. * @hidden
  39967. */
  39968. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39969. __extends(_PrimitiveGeometry, _super);
  39970. /**
  39971. * Creates a new typed geometry
  39972. * @param id defines the unique ID of the geometry
  39973. * @param scene defines the hosting scene
  39974. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39975. * @param mesh defines the hosting mesh (can be null)
  39976. */
  39977. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39978. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39979. if (mesh === void 0) { mesh = null; }
  39980. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39981. _this._canBeRegenerated = _canBeRegenerated;
  39982. _this._beingRegenerated = true;
  39983. _this.regenerate();
  39984. _this._beingRegenerated = false;
  39985. return _this;
  39986. }
  39987. /**
  39988. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39989. * @returns true if the geometry can be regenerated
  39990. */
  39991. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39992. return this._canBeRegenerated;
  39993. };
  39994. /**
  39995. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39996. */
  39997. _PrimitiveGeometry.prototype.regenerate = function () {
  39998. if (!this._canBeRegenerated) {
  39999. return;
  40000. }
  40001. this._beingRegenerated = true;
  40002. this.setAllVerticesData(this._regenerateVertexData(), false);
  40003. this._beingRegenerated = false;
  40004. };
  40005. /**
  40006. * Clone the geometry
  40007. * @param id defines the unique ID of the new geometry
  40008. * @returns the new geometry
  40009. */
  40010. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40011. return _super.prototype.copy.call(this, id);
  40012. };
  40013. // overrides
  40014. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40015. if (!this._beingRegenerated) {
  40016. return;
  40017. }
  40018. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40019. };
  40020. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40021. if (!this._beingRegenerated) {
  40022. return;
  40023. }
  40024. _super.prototype.setVerticesData.call(this, kind, data, false);
  40025. };
  40026. // to override
  40027. /** @hidden */
  40028. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40029. throw new Error("Abstract method");
  40030. };
  40031. _PrimitiveGeometry.prototype.copy = function (id) {
  40032. throw new Error("Must be overriden in sub-classes.");
  40033. };
  40034. _PrimitiveGeometry.prototype.serialize = function () {
  40035. var serializationObject = _super.prototype.serialize.call(this);
  40036. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40037. return serializationObject;
  40038. };
  40039. return _PrimitiveGeometry;
  40040. }(Geometry));
  40041. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40042. /**
  40043. * Creates a ribbon geometry
  40044. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40045. */
  40046. var RibbonGeometry = /** @class */ (function (_super) {
  40047. __extends(RibbonGeometry, _super);
  40048. /**
  40049. * Creates a ribbon geometry
  40050. * @param id defines the unique ID of the geometry
  40051. * @param scene defines the hosting scene
  40052. * @param pathArray defines the array of paths to use
  40053. * @param closeArray defines if the last path and the first path must be joined
  40054. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40055. * @param offset defines the offset between points
  40056. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40057. * @param mesh defines the hosting mesh (can be null)
  40058. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40059. */
  40060. function RibbonGeometry(id, scene,
  40061. /**
  40062. * Defines the array of paths to use
  40063. */
  40064. pathArray,
  40065. /**
  40066. * Defines if the last and first points of each path in your pathArray must be joined
  40067. */
  40068. closeArray,
  40069. /**
  40070. * Defines if the last and first points of each path in your pathArray must be joined
  40071. */
  40072. closePath,
  40073. /**
  40074. * Defines the offset between points
  40075. */
  40076. offset, canBeRegenerated, mesh,
  40077. /**
  40078. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40079. */
  40080. side) {
  40081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40083. _this.pathArray = pathArray;
  40084. _this.closeArray = closeArray;
  40085. _this.closePath = closePath;
  40086. _this.offset = offset;
  40087. _this.side = side;
  40088. return _this;
  40089. }
  40090. /** @hidden */
  40091. RibbonGeometry.prototype._regenerateVertexData = function () {
  40092. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40093. };
  40094. RibbonGeometry.prototype.copy = function (id) {
  40095. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40096. };
  40097. return RibbonGeometry;
  40098. }(_PrimitiveGeometry));
  40099. BABYLON.RibbonGeometry = RibbonGeometry;
  40100. /**
  40101. * Creates a box geometry
  40102. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40103. */
  40104. var BoxGeometry = /** @class */ (function (_super) {
  40105. __extends(BoxGeometry, _super);
  40106. /**
  40107. * Creates a box geometry
  40108. * @param id defines the unique ID of the geometry
  40109. * @param scene defines the hosting scene
  40110. * @param size defines the zise of the box (width, height and depth are the same)
  40111. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40112. * @param mesh defines the hosting mesh (can be null)
  40113. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40114. */
  40115. function BoxGeometry(id, scene,
  40116. /**
  40117. * Defines the zise of the box (width, height and depth are the same)
  40118. */
  40119. size, canBeRegenerated, mesh,
  40120. /**
  40121. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40122. */
  40123. side) {
  40124. if (mesh === void 0) { mesh = null; }
  40125. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40126. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40127. _this.size = size;
  40128. _this.side = side;
  40129. return _this;
  40130. }
  40131. /** @hidden */
  40132. BoxGeometry.prototype._regenerateVertexData = function () {
  40133. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40134. };
  40135. BoxGeometry.prototype.copy = function (id) {
  40136. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40137. };
  40138. BoxGeometry.prototype.serialize = function () {
  40139. var serializationObject = _super.prototype.serialize.call(this);
  40140. serializationObject.size = this.size;
  40141. return serializationObject;
  40142. };
  40143. BoxGeometry.Parse = function (parsedBox, scene) {
  40144. if (scene.getGeometryByID(parsedBox.id)) {
  40145. return null; // null since geometry could be something else than a box...
  40146. }
  40147. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40148. if (BABYLON.Tags) {
  40149. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40150. }
  40151. scene.pushGeometry(box, true);
  40152. return box;
  40153. };
  40154. return BoxGeometry;
  40155. }(_PrimitiveGeometry));
  40156. BABYLON.BoxGeometry = BoxGeometry;
  40157. /**
  40158. * Creates a sphere geometry
  40159. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40160. */
  40161. var SphereGeometry = /** @class */ (function (_super) {
  40162. __extends(SphereGeometry, _super);
  40163. /**
  40164. * Create a new sphere geometry
  40165. * @param id defines the unique ID of the geometry
  40166. * @param scene defines the hosting scene
  40167. * @param segments defines the number of segments to use to create the sphere
  40168. * @param diameter defines the diameter of the sphere
  40169. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40170. * @param mesh defines the hosting mesh (can be null)
  40171. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40172. */
  40173. function SphereGeometry(id, scene,
  40174. /**
  40175. * Defines the number of segments to use to create the sphere
  40176. */
  40177. segments,
  40178. /**
  40179. * Defines the diameter of the sphere
  40180. */
  40181. diameter, canBeRegenerated, mesh,
  40182. /**
  40183. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40184. */
  40185. side) {
  40186. if (mesh === void 0) { mesh = null; }
  40187. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40188. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40189. _this.segments = segments;
  40190. _this.diameter = diameter;
  40191. _this.side = side;
  40192. return _this;
  40193. }
  40194. /** @hidden */
  40195. SphereGeometry.prototype._regenerateVertexData = function () {
  40196. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40197. };
  40198. SphereGeometry.prototype.copy = function (id) {
  40199. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40200. };
  40201. SphereGeometry.prototype.serialize = function () {
  40202. var serializationObject = _super.prototype.serialize.call(this);
  40203. serializationObject.segments = this.segments;
  40204. serializationObject.diameter = this.diameter;
  40205. return serializationObject;
  40206. };
  40207. SphereGeometry.Parse = function (parsedSphere, scene) {
  40208. if (scene.getGeometryByID(parsedSphere.id)) {
  40209. return null; // null since geometry could be something else than a sphere...
  40210. }
  40211. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40212. if (BABYLON.Tags) {
  40213. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40214. }
  40215. scene.pushGeometry(sphere, true);
  40216. return sphere;
  40217. };
  40218. return SphereGeometry;
  40219. }(_PrimitiveGeometry));
  40220. BABYLON.SphereGeometry = SphereGeometry;
  40221. /**
  40222. * Creates a disc geometry
  40223. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40224. */
  40225. var DiscGeometry = /** @class */ (function (_super) {
  40226. __extends(DiscGeometry, _super);
  40227. /**
  40228. * Creates a new disc geometry
  40229. * @param id defines the unique ID of the geometry
  40230. * @param scene defines the hosting scene
  40231. * @param radius defines the radius of the disc
  40232. * @param tessellation defines the tesselation factor to apply to the disc
  40233. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40234. * @param mesh defines the hosting mesh (can be null)
  40235. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40236. */
  40237. function DiscGeometry(id, scene,
  40238. /**
  40239. * Defines the radius of the disc
  40240. */
  40241. radius,
  40242. /**
  40243. * Defines the tesselation factor to apply to the disc
  40244. */
  40245. tessellation, canBeRegenerated, mesh,
  40246. /**
  40247. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40248. */
  40249. side) {
  40250. if (mesh === void 0) { mesh = null; }
  40251. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40252. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40253. _this.radius = radius;
  40254. _this.tessellation = tessellation;
  40255. _this.side = side;
  40256. return _this;
  40257. }
  40258. /** @hidden */
  40259. DiscGeometry.prototype._regenerateVertexData = function () {
  40260. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40261. };
  40262. DiscGeometry.prototype.copy = function (id) {
  40263. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40264. };
  40265. return DiscGeometry;
  40266. }(_PrimitiveGeometry));
  40267. BABYLON.DiscGeometry = DiscGeometry;
  40268. /**
  40269. * Creates a new cylinder geometry
  40270. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40271. */
  40272. var CylinderGeometry = /** @class */ (function (_super) {
  40273. __extends(CylinderGeometry, _super);
  40274. /**
  40275. * Creates a new cylinder geometry
  40276. * @param id defines the unique ID of the geometry
  40277. * @param scene defines the hosting scene
  40278. * @param height defines the height of the cylinder
  40279. * @param diameterTop defines the diameter of the cylinder's top cap
  40280. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40281. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40282. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40283. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40284. * @param mesh defines the hosting mesh (can be null)
  40285. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40286. */
  40287. function CylinderGeometry(id, scene,
  40288. /**
  40289. * Defines the height of the cylinder
  40290. */
  40291. height,
  40292. /**
  40293. * Defines the diameter of the cylinder's top cap
  40294. */
  40295. diameterTop,
  40296. /**
  40297. * Defines the diameter of the cylinder's bottom cap
  40298. */
  40299. diameterBottom,
  40300. /**
  40301. * Defines the tessellation factor to apply to the cylinder
  40302. */
  40303. tessellation,
  40304. /**
  40305. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40306. */
  40307. subdivisions, canBeRegenerated, mesh,
  40308. /**
  40309. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40310. */
  40311. side) {
  40312. if (subdivisions === void 0) { subdivisions = 1; }
  40313. if (mesh === void 0) { mesh = null; }
  40314. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40315. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40316. _this.height = height;
  40317. _this.diameterTop = diameterTop;
  40318. _this.diameterBottom = diameterBottom;
  40319. _this.tessellation = tessellation;
  40320. _this.subdivisions = subdivisions;
  40321. _this.side = side;
  40322. return _this;
  40323. }
  40324. /** @hidden */
  40325. CylinderGeometry.prototype._regenerateVertexData = function () {
  40326. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40327. };
  40328. CylinderGeometry.prototype.copy = function (id) {
  40329. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40330. };
  40331. CylinderGeometry.prototype.serialize = function () {
  40332. var serializationObject = _super.prototype.serialize.call(this);
  40333. serializationObject.height = this.height;
  40334. serializationObject.diameterTop = this.diameterTop;
  40335. serializationObject.diameterBottom = this.diameterBottom;
  40336. serializationObject.tessellation = this.tessellation;
  40337. return serializationObject;
  40338. };
  40339. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40340. if (scene.getGeometryByID(parsedCylinder.id)) {
  40341. return null; // null since geometry could be something else than a cylinder...
  40342. }
  40343. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40344. if (BABYLON.Tags) {
  40345. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40346. }
  40347. scene.pushGeometry(cylinder, true);
  40348. return cylinder;
  40349. };
  40350. return CylinderGeometry;
  40351. }(_PrimitiveGeometry));
  40352. BABYLON.CylinderGeometry = CylinderGeometry;
  40353. /**
  40354. * Creates a new torus geometry
  40355. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40356. */
  40357. var TorusGeometry = /** @class */ (function (_super) {
  40358. __extends(TorusGeometry, _super);
  40359. /**
  40360. * Creates a new torus geometry
  40361. * @param id defines the unique ID of the geometry
  40362. * @param scene defines the hosting scene
  40363. * @param diameter defines the diameter of the torus
  40364. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40365. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40366. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40367. * @param mesh defines the hosting mesh (can be null)
  40368. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40369. */
  40370. function TorusGeometry(id, scene,
  40371. /**
  40372. * Defines the diameter of the torus
  40373. */
  40374. diameter,
  40375. /**
  40376. * Defines the thickness of the torus (ie. internal diameter)
  40377. */
  40378. thickness,
  40379. /**
  40380. * Defines the tesselation factor to apply to the torus
  40381. */
  40382. tessellation, canBeRegenerated, mesh,
  40383. /**
  40384. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40385. */
  40386. side) {
  40387. if (mesh === void 0) { mesh = null; }
  40388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40390. _this.diameter = diameter;
  40391. _this.thickness = thickness;
  40392. _this.tessellation = tessellation;
  40393. _this.side = side;
  40394. return _this;
  40395. }
  40396. /** @hidden */
  40397. TorusGeometry.prototype._regenerateVertexData = function () {
  40398. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40399. };
  40400. TorusGeometry.prototype.copy = function (id) {
  40401. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40402. };
  40403. TorusGeometry.prototype.serialize = function () {
  40404. var serializationObject = _super.prototype.serialize.call(this);
  40405. serializationObject.diameter = this.diameter;
  40406. serializationObject.thickness = this.thickness;
  40407. serializationObject.tessellation = this.tessellation;
  40408. return serializationObject;
  40409. };
  40410. TorusGeometry.Parse = function (parsedTorus, scene) {
  40411. if (scene.getGeometryByID(parsedTorus.id)) {
  40412. return null; // null since geometry could be something else than a torus...
  40413. }
  40414. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40415. if (BABYLON.Tags) {
  40416. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40417. }
  40418. scene.pushGeometry(torus, true);
  40419. return torus;
  40420. };
  40421. return TorusGeometry;
  40422. }(_PrimitiveGeometry));
  40423. BABYLON.TorusGeometry = TorusGeometry;
  40424. /**
  40425. * Creates a new ground geometry
  40426. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40427. */
  40428. var GroundGeometry = /** @class */ (function (_super) {
  40429. __extends(GroundGeometry, _super);
  40430. /**
  40431. * Creates a new ground geometry
  40432. * @param id defines the unique ID of the geometry
  40433. * @param scene defines the hosting scene
  40434. * @param width defines the width of the ground
  40435. * @param height defines the height of the ground
  40436. * @param subdivisions defines the subdivisions to apply to the ground
  40437. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40438. * @param mesh defines the hosting mesh (can be null)
  40439. */
  40440. function GroundGeometry(id, scene,
  40441. /**
  40442. * Defines the width of the ground
  40443. */
  40444. width,
  40445. /**
  40446. * Defines the height of the ground
  40447. */
  40448. height,
  40449. /**
  40450. * Defines the subdivisions to apply to the ground
  40451. */
  40452. subdivisions, canBeRegenerated, mesh) {
  40453. if (mesh === void 0) { mesh = null; }
  40454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40455. _this.width = width;
  40456. _this.height = height;
  40457. _this.subdivisions = subdivisions;
  40458. return _this;
  40459. }
  40460. /** @hidden */
  40461. GroundGeometry.prototype._regenerateVertexData = function () {
  40462. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40463. };
  40464. GroundGeometry.prototype.copy = function (id) {
  40465. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40466. };
  40467. GroundGeometry.prototype.serialize = function () {
  40468. var serializationObject = _super.prototype.serialize.call(this);
  40469. serializationObject.width = this.width;
  40470. serializationObject.height = this.height;
  40471. serializationObject.subdivisions = this.subdivisions;
  40472. return serializationObject;
  40473. };
  40474. GroundGeometry.Parse = function (parsedGround, scene) {
  40475. if (scene.getGeometryByID(parsedGround.id)) {
  40476. return null; // null since geometry could be something else than a ground...
  40477. }
  40478. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40479. if (BABYLON.Tags) {
  40480. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40481. }
  40482. scene.pushGeometry(ground, true);
  40483. return ground;
  40484. };
  40485. return GroundGeometry;
  40486. }(_PrimitiveGeometry));
  40487. BABYLON.GroundGeometry = GroundGeometry;
  40488. /**
  40489. * Creates a tiled ground geometry
  40490. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40491. */
  40492. var TiledGroundGeometry = /** @class */ (function (_super) {
  40493. __extends(TiledGroundGeometry, _super);
  40494. /**
  40495. * Creates a tiled ground geometry
  40496. * @param id defines the unique ID of the geometry
  40497. * @param scene defines the hosting scene
  40498. * @param xmin defines the minimum value on X axis
  40499. * @param zmin defines the minimum value on Z axis
  40500. * @param xmax defines the maximum value on X axis
  40501. * @param zmax defines the maximum value on Z axis
  40502. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40503. * @param precision defines the precision to use when computing the tiles
  40504. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40505. * @param mesh defines the hosting mesh (can be null)
  40506. */
  40507. function TiledGroundGeometry(id, scene,
  40508. /**
  40509. * Defines the minimum value on X axis
  40510. */
  40511. xmin,
  40512. /**
  40513. * Defines the minimum value on Z axis
  40514. */
  40515. zmin,
  40516. /**
  40517. * Defines the maximum value on X axis
  40518. */
  40519. xmax,
  40520. /**
  40521. * Defines the maximum value on Z axis
  40522. */
  40523. zmax,
  40524. /**
  40525. * Defines the subdivisions to apply to the ground
  40526. */
  40527. subdivisions,
  40528. /**
  40529. * Defines the precision to use when computing the tiles
  40530. */
  40531. precision, canBeRegenerated, mesh) {
  40532. if (mesh === void 0) { mesh = null; }
  40533. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40534. _this.xmin = xmin;
  40535. _this.zmin = zmin;
  40536. _this.xmax = xmax;
  40537. _this.zmax = zmax;
  40538. _this.subdivisions = subdivisions;
  40539. _this.precision = precision;
  40540. return _this;
  40541. }
  40542. /** @hidden */
  40543. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40544. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40545. };
  40546. TiledGroundGeometry.prototype.copy = function (id) {
  40547. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40548. };
  40549. return TiledGroundGeometry;
  40550. }(_PrimitiveGeometry));
  40551. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40552. /**
  40553. * Creates a plane geometry
  40554. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40555. */
  40556. var PlaneGeometry = /** @class */ (function (_super) {
  40557. __extends(PlaneGeometry, _super);
  40558. /**
  40559. * Creates a plane geometry
  40560. * @param id defines the unique ID of the geometry
  40561. * @param scene defines the hosting scene
  40562. * @param size defines the size of the plane (width === height)
  40563. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40564. * @param mesh defines the hosting mesh (can be null)
  40565. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40566. */
  40567. function PlaneGeometry(id, scene,
  40568. /**
  40569. * Defines the size of the plane (width === height)
  40570. */
  40571. size, canBeRegenerated, mesh,
  40572. /**
  40573. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40574. */
  40575. side) {
  40576. if (mesh === void 0) { mesh = null; }
  40577. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40578. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40579. _this.size = size;
  40580. _this.side = side;
  40581. return _this;
  40582. }
  40583. /** @hidden */
  40584. PlaneGeometry.prototype._regenerateVertexData = function () {
  40585. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40586. };
  40587. PlaneGeometry.prototype.copy = function (id) {
  40588. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40589. };
  40590. PlaneGeometry.prototype.serialize = function () {
  40591. var serializationObject = _super.prototype.serialize.call(this);
  40592. serializationObject.size = this.size;
  40593. return serializationObject;
  40594. };
  40595. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40596. if (scene.getGeometryByID(parsedPlane.id)) {
  40597. return null; // null since geometry could be something else than a ground...
  40598. }
  40599. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40600. if (BABYLON.Tags) {
  40601. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40602. }
  40603. scene.pushGeometry(plane, true);
  40604. return plane;
  40605. };
  40606. return PlaneGeometry;
  40607. }(_PrimitiveGeometry));
  40608. BABYLON.PlaneGeometry = PlaneGeometry;
  40609. /**
  40610. * Creates a torus knot geometry
  40611. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40612. */
  40613. var TorusKnotGeometry = /** @class */ (function (_super) {
  40614. __extends(TorusKnotGeometry, _super);
  40615. /**
  40616. * Creates a torus knot geometry
  40617. * @param id defines the unique ID of the geometry
  40618. * @param scene defines the hosting scene
  40619. * @param radius defines the radius of the torus knot
  40620. * @param tube defines the thickness of the torus knot tube
  40621. * @param radialSegments defines the number of radial segments
  40622. * @param tubularSegments defines the number of tubular segments
  40623. * @param p defines the first number of windings
  40624. * @param q defines the second number of windings
  40625. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40626. * @param mesh defines the hosting mesh (can be null)
  40627. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40628. */
  40629. function TorusKnotGeometry(id, scene,
  40630. /**
  40631. * Defines the radius of the torus knot
  40632. */
  40633. radius,
  40634. /**
  40635. * Defines the thickness of the torus knot tube
  40636. */
  40637. tube,
  40638. /**
  40639. * Defines the number of radial segments
  40640. */
  40641. radialSegments,
  40642. /**
  40643. * Defines the number of tubular segments
  40644. */
  40645. tubularSegments,
  40646. /**
  40647. * Defines the first number of windings
  40648. */
  40649. p,
  40650. /**
  40651. * Defines the second number of windings
  40652. */
  40653. q, canBeRegenerated, mesh,
  40654. /**
  40655. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40656. */
  40657. side) {
  40658. if (mesh === void 0) { mesh = null; }
  40659. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40660. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40661. _this.radius = radius;
  40662. _this.tube = tube;
  40663. _this.radialSegments = radialSegments;
  40664. _this.tubularSegments = tubularSegments;
  40665. _this.p = p;
  40666. _this.q = q;
  40667. _this.side = side;
  40668. return _this;
  40669. }
  40670. /** @hidden */
  40671. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40672. 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 });
  40673. };
  40674. TorusKnotGeometry.prototype.copy = function (id) {
  40675. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40676. };
  40677. TorusKnotGeometry.prototype.serialize = function () {
  40678. var serializationObject = _super.prototype.serialize.call(this);
  40679. serializationObject.radius = this.radius;
  40680. serializationObject.tube = this.tube;
  40681. serializationObject.radialSegments = this.radialSegments;
  40682. serializationObject.tubularSegments = this.tubularSegments;
  40683. serializationObject.p = this.p;
  40684. serializationObject.q = this.q;
  40685. return serializationObject;
  40686. };
  40687. ;
  40688. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40689. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40690. return null; // null since geometry could be something else than a ground...
  40691. }
  40692. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40693. if (BABYLON.Tags) {
  40694. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40695. }
  40696. scene.pushGeometry(torusKnot, true);
  40697. return torusKnot;
  40698. };
  40699. return TorusKnotGeometry;
  40700. }(_PrimitiveGeometry));
  40701. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40702. //}
  40703. })(BABYLON || (BABYLON = {}));
  40704. //# sourceMappingURL=babylon.geometry.js.map
  40705. var BABYLON;
  40706. (function (BABYLON) {
  40707. /**
  40708. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40709. */
  40710. var PerformanceMonitor = /** @class */ (function () {
  40711. /**
  40712. * constructor
  40713. * @param frameSampleSize The number of samples required to saturate the sliding window
  40714. */
  40715. function PerformanceMonitor(frameSampleSize) {
  40716. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40717. this._enabled = true;
  40718. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40719. }
  40720. /**
  40721. * Samples current frame
  40722. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40723. */
  40724. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40725. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40726. if (!this._enabled)
  40727. return;
  40728. if (this._lastFrameTimeMs != null) {
  40729. var dt = timeMs - this._lastFrameTimeMs;
  40730. this._rollingFrameTime.add(dt);
  40731. }
  40732. this._lastFrameTimeMs = timeMs;
  40733. };
  40734. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40735. /**
  40736. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40737. * @return Average frame time in milliseconds
  40738. */
  40739. get: function () {
  40740. return this._rollingFrameTime.average;
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40746. /**
  40747. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40748. * @return Frame time variance in milliseconds squared
  40749. */
  40750. get: function () {
  40751. return this._rollingFrameTime.variance;
  40752. },
  40753. enumerable: true,
  40754. configurable: true
  40755. });
  40756. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40757. /**
  40758. * Returns the frame time of the most recent frame
  40759. * @return Frame time in milliseconds
  40760. */
  40761. get: function () {
  40762. return this._rollingFrameTime.history(0);
  40763. },
  40764. enumerable: true,
  40765. configurable: true
  40766. });
  40767. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40768. /**
  40769. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40770. * @return Framerate in frames per second
  40771. */
  40772. get: function () {
  40773. return 1000.0 / this._rollingFrameTime.average;
  40774. },
  40775. enumerable: true,
  40776. configurable: true
  40777. });
  40778. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40779. /**
  40780. * Returns the average framerate in frames per second using the most recent frame time
  40781. * @return Framerate in frames per second
  40782. */
  40783. get: function () {
  40784. var history = this._rollingFrameTime.history(0);
  40785. if (history === 0) {
  40786. return 0;
  40787. }
  40788. return 1000.0 / history;
  40789. },
  40790. enumerable: true,
  40791. configurable: true
  40792. });
  40793. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40794. /**
  40795. * Returns true if enough samples have been taken to completely fill the sliding window
  40796. * @return true if saturated
  40797. */
  40798. get: function () {
  40799. return this._rollingFrameTime.isSaturated();
  40800. },
  40801. enumerable: true,
  40802. configurable: true
  40803. });
  40804. /**
  40805. * Enables contributions to the sliding window sample set
  40806. */
  40807. PerformanceMonitor.prototype.enable = function () {
  40808. this._enabled = true;
  40809. };
  40810. /**
  40811. * Disables contributions to the sliding window sample set
  40812. * Samples will not be interpolated over the disabled period
  40813. */
  40814. PerformanceMonitor.prototype.disable = function () {
  40815. this._enabled = false;
  40816. //clear last sample to avoid interpolating over the disabled period when next enabled
  40817. this._lastFrameTimeMs = null;
  40818. };
  40819. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40820. /**
  40821. * Returns true if sampling is enabled
  40822. * @return true if enabled
  40823. */
  40824. get: function () {
  40825. return this._enabled;
  40826. },
  40827. enumerable: true,
  40828. configurable: true
  40829. });
  40830. /**
  40831. * Resets performance monitor
  40832. */
  40833. PerformanceMonitor.prototype.reset = function () {
  40834. //clear last sample to avoid interpolating over the disabled period when next enabled
  40835. this._lastFrameTimeMs = null;
  40836. //wipe record
  40837. this._rollingFrameTime.reset();
  40838. };
  40839. return PerformanceMonitor;
  40840. }());
  40841. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40842. /**
  40843. * RollingAverage
  40844. *
  40845. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40846. */
  40847. var RollingAverage = /** @class */ (function () {
  40848. /**
  40849. * constructor
  40850. * @param length The number of samples required to saturate the sliding window
  40851. */
  40852. function RollingAverage(length) {
  40853. this._samples = new Array(length);
  40854. this.reset();
  40855. }
  40856. /**
  40857. * Adds a sample to the sample set
  40858. * @param v The sample value
  40859. */
  40860. RollingAverage.prototype.add = function (v) {
  40861. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40862. var delta;
  40863. //we need to check if we've already wrapped round
  40864. if (this.isSaturated()) {
  40865. //remove bottom of stack from mean
  40866. var bottomValue = this._samples[this._pos];
  40867. delta = bottomValue - this.average;
  40868. this.average -= delta / (this._sampleCount - 1);
  40869. this._m2 -= delta * (bottomValue - this.average);
  40870. }
  40871. else {
  40872. this._sampleCount++;
  40873. }
  40874. //add new value to mean
  40875. delta = v - this.average;
  40876. this.average += delta / (this._sampleCount);
  40877. this._m2 += delta * (v - this.average);
  40878. //set the new variance
  40879. this.variance = this._m2 / (this._sampleCount - 1);
  40880. this._samples[this._pos] = v;
  40881. this._pos++;
  40882. this._pos %= this._samples.length; //positive wrap around
  40883. };
  40884. /**
  40885. * Returns previously added values or null if outside of history or outside the sliding window domain
  40886. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40887. * @return Value previously recorded with add() or null if outside of range
  40888. */
  40889. RollingAverage.prototype.history = function (i) {
  40890. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40891. return 0;
  40892. }
  40893. var i0 = this._wrapPosition(this._pos - 1.0);
  40894. return this._samples[this._wrapPosition(i0 - i)];
  40895. };
  40896. /**
  40897. * Returns true if enough samples have been taken to completely fill the sliding window
  40898. * @return true if sample-set saturated
  40899. */
  40900. RollingAverage.prototype.isSaturated = function () {
  40901. return this._sampleCount >= this._samples.length;
  40902. };
  40903. /**
  40904. * Resets the rolling average (equivalent to 0 samples taken so far)
  40905. */
  40906. RollingAverage.prototype.reset = function () {
  40907. this.average = 0;
  40908. this.variance = 0;
  40909. this._sampleCount = 0;
  40910. this._pos = 0;
  40911. this._m2 = 0;
  40912. };
  40913. /**
  40914. * Wraps a value around the sample range boundaries
  40915. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40916. * @return Wrapped position in sample range
  40917. */
  40918. RollingAverage.prototype._wrapPosition = function (i) {
  40919. var max = this._samples.length;
  40920. return ((i % max) + max) % max;
  40921. };
  40922. return RollingAverage;
  40923. }());
  40924. BABYLON.RollingAverage = RollingAverage;
  40925. })(BABYLON || (BABYLON = {}));
  40926. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40927. var BABYLON;
  40928. (function (BABYLON) {
  40929. /**
  40930. * "Static Class" containing the most commonly used helper while dealing with material for
  40931. * rendering purpose.
  40932. *
  40933. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40934. *
  40935. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40936. */
  40937. var MaterialHelper = /** @class */ (function () {
  40938. function MaterialHelper() {
  40939. }
  40940. /**
  40941. * Bind the current view position to an effect.
  40942. * @param effect The effect to be bound
  40943. * @param scene The scene the eyes position is used from
  40944. */
  40945. MaterialHelper.BindEyePosition = function (effect, scene) {
  40946. if (scene._forcedViewPosition) {
  40947. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40948. return;
  40949. }
  40950. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40951. };
  40952. /**
  40953. * Helps preparing the defines values about the UVs in used in the effect.
  40954. * UVs are shared as much as we can accross chanels in the shaders.
  40955. * @param texture The texture we are preparing the UVs for
  40956. * @param defines The defines to update
  40957. * @param key The chanel key "diffuse", "specular"... used in the shader
  40958. */
  40959. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40960. defines._needUVs = true;
  40961. defines[key] = true;
  40962. if (texture.getTextureMatrix().isIdentity(true)) {
  40963. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40964. if (texture.coordinatesIndex === 0) {
  40965. defines["MAINUV1"] = true;
  40966. }
  40967. else {
  40968. defines["MAINUV2"] = true;
  40969. }
  40970. }
  40971. else {
  40972. defines[key + "DIRECTUV"] = 0;
  40973. }
  40974. };
  40975. /**
  40976. * Binds a texture matrix value to its corrsponding uniform
  40977. * @param texture The texture to bind the matrix for
  40978. * @param uniformBuffer The uniform buffer receivin the data
  40979. * @param key The chanel key "diffuse", "specular"... used in the shader
  40980. */
  40981. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40982. var matrix = texture.getTextureMatrix();
  40983. if (!matrix.isIdentity(true)) {
  40984. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40985. }
  40986. };
  40987. /**
  40988. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40989. * @param mesh defines the current mesh
  40990. * @param scene defines the current scene
  40991. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40992. * @param pointsCloud defines if point cloud rendering has to be turned on
  40993. * @param fogEnabled defines if fog has to be turned on
  40994. * @param alphaTest defines if alpha testing has to be turned on
  40995. * @param defines defines the current list of defines
  40996. */
  40997. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40998. if (defines._areMiscDirty) {
  40999. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41000. defines["POINTSIZE"] = pointsCloud;
  41001. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41002. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41003. defines["ALPHATEST"] = alphaTest;
  41004. }
  41005. };
  41006. /**
  41007. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41008. * @param scene defines the current scene
  41009. * @param engine defines the current engine
  41010. * @param defines specifies the list of active defines
  41011. * @param useInstances defines if instances have to be turned on
  41012. * @param useClipPlane defines if clip plane have to be turned on
  41013. */
  41014. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41015. if (useClipPlane === void 0) { useClipPlane = null; }
  41016. var changed = false;
  41017. var useClipPlane1 = false;
  41018. var useClipPlane2 = false;
  41019. var useClipPlane3 = false;
  41020. var useClipPlane4 = false;
  41021. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41022. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41023. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41024. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41025. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41026. defines["CLIPPLANE"] = useClipPlane1;
  41027. changed = true;
  41028. }
  41029. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41030. defines["CLIPPLANE2"] = useClipPlane2;
  41031. changed = true;
  41032. }
  41033. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41034. defines["CLIPPLANE3"] = useClipPlane3;
  41035. changed = true;
  41036. }
  41037. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41038. defines["CLIPPLANE4"] = useClipPlane4;
  41039. changed = true;
  41040. }
  41041. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41042. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41043. changed = true;
  41044. }
  41045. if (defines["INSTANCES"] !== useInstances) {
  41046. defines["INSTANCES"] = useInstances;
  41047. changed = true;
  41048. }
  41049. if (changed) {
  41050. defines.markAsUnprocessed();
  41051. }
  41052. };
  41053. /**
  41054. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41055. * @param mesh The mesh containing the geometry data we will draw
  41056. * @param defines The defines to update
  41057. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41058. * @param useBones Precise whether bones should be used or not (override mesh info)
  41059. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41060. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41061. * @returns false if defines are considered not dirty and have not been checked
  41062. */
  41063. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41064. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41065. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41066. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41067. return false;
  41068. }
  41069. defines._normals = defines._needNormals;
  41070. defines._uvs = defines._needUVs;
  41071. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41072. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41073. defines["TANGENT"] = true;
  41074. }
  41075. if (defines._needUVs) {
  41076. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41077. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41078. }
  41079. else {
  41080. defines["UV1"] = false;
  41081. defines["UV2"] = false;
  41082. }
  41083. if (useVertexColor) {
  41084. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41085. defines["VERTEXCOLOR"] = hasVertexColors;
  41086. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41087. }
  41088. if (useBones) {
  41089. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41090. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41091. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41092. }
  41093. else {
  41094. defines["NUM_BONE_INFLUENCERS"] = 0;
  41095. defines["BonesPerMesh"] = 0;
  41096. }
  41097. }
  41098. if (useMorphTargets) {
  41099. var manager = mesh.morphTargetManager;
  41100. if (manager) {
  41101. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41102. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41103. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41104. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41105. }
  41106. else {
  41107. defines["MORPHTARGETS_TANGENT"] = false;
  41108. defines["MORPHTARGETS_NORMAL"] = false;
  41109. defines["MORPHTARGETS"] = false;
  41110. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41111. }
  41112. }
  41113. return true;
  41114. };
  41115. /**
  41116. * Prepares the defines related to the light information passed in parameter
  41117. * @param scene The scene we are intending to draw
  41118. * @param mesh The mesh the effect is compiling for
  41119. * @param defines The defines to update
  41120. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41121. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41122. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41123. * @returns true if normals will be required for the rest of the effect
  41124. */
  41125. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41126. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41127. if (disableLighting === void 0) { disableLighting = false; }
  41128. if (!defines._areLightsDirty) {
  41129. return defines._needNormals;
  41130. }
  41131. var lightIndex = 0;
  41132. var needNormals = false;
  41133. var needRebuild = false;
  41134. var lightmapMode = false;
  41135. var shadowEnabled = false;
  41136. var specularEnabled = false;
  41137. if (scene.lightsEnabled && !disableLighting) {
  41138. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41139. var light = _a[_i];
  41140. needNormals = true;
  41141. if (defines["LIGHT" + lightIndex] === undefined) {
  41142. needRebuild = true;
  41143. }
  41144. defines["LIGHT" + lightIndex] = true;
  41145. defines["SPOTLIGHT" + lightIndex] = false;
  41146. defines["HEMILIGHT" + lightIndex] = false;
  41147. defines["POINTLIGHT" + lightIndex] = false;
  41148. defines["DIRLIGHT" + lightIndex] = false;
  41149. light.prepareLightSpecificDefines(defines, lightIndex);
  41150. // FallOff.
  41151. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41152. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41153. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41154. switch (light.falloffType) {
  41155. case BABYLON.Light.FALLOFF_GLTF:
  41156. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41157. break;
  41158. case BABYLON.Light.FALLOFF_PHYSICAL:
  41159. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41160. break;
  41161. case BABYLON.Light.FALLOFF_STANDARD:
  41162. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41163. break;
  41164. }
  41165. // Specular
  41166. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41167. specularEnabled = true;
  41168. }
  41169. // Shadows
  41170. defines["SHADOW" + lightIndex] = false;
  41171. defines["SHADOWPCF" + lightIndex] = false;
  41172. defines["SHADOWPCSS" + lightIndex] = false;
  41173. defines["SHADOWPOISSON" + lightIndex] = false;
  41174. defines["SHADOWESM" + lightIndex] = false;
  41175. defines["SHADOWCUBE" + lightIndex] = false;
  41176. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41177. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41178. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41179. var shadowGenerator = light.getShadowGenerator();
  41180. if (shadowGenerator) {
  41181. var shadowMap = shadowGenerator.getShadowMap();
  41182. if (shadowMap) {
  41183. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41184. shadowEnabled = true;
  41185. shadowGenerator.prepareDefines(defines, lightIndex);
  41186. }
  41187. }
  41188. }
  41189. }
  41190. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41191. lightmapMode = true;
  41192. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41193. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41194. }
  41195. else {
  41196. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41197. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41198. }
  41199. lightIndex++;
  41200. if (lightIndex === maxSimultaneousLights)
  41201. break;
  41202. }
  41203. }
  41204. defines["SPECULARTERM"] = specularEnabled;
  41205. defines["SHADOWS"] = shadowEnabled;
  41206. // Resetting all other lights if any
  41207. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41208. if (defines["LIGHT" + index] !== undefined) {
  41209. defines["LIGHT" + index] = false;
  41210. defines["HEMILIGHT" + lightIndex] = false;
  41211. defines["POINTLIGHT" + lightIndex] = false;
  41212. defines["DIRLIGHT" + lightIndex] = false;
  41213. defines["SPOTLIGHT" + lightIndex] = false;
  41214. defines["SHADOW" + lightIndex] = false;
  41215. }
  41216. }
  41217. var caps = scene.getEngine().getCaps();
  41218. if (defines["SHADOWFLOAT"] === undefined) {
  41219. needRebuild = true;
  41220. }
  41221. defines["SHADOWFLOAT"] = shadowEnabled &&
  41222. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41223. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41224. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41225. if (needRebuild) {
  41226. defines.rebuild();
  41227. }
  41228. return needNormals;
  41229. };
  41230. /**
  41231. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41232. * that won t be acctive due to defines being turned off.
  41233. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41234. * @param samplersList The samplers list
  41235. * @param defines The defines helping in the list generation
  41236. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41237. */
  41238. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41239. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41240. var uniformsList;
  41241. var uniformBuffersList = null;
  41242. if (uniformsListOrOptions.uniformsNames) {
  41243. var options = uniformsListOrOptions;
  41244. uniformsList = options.uniformsNames;
  41245. uniformBuffersList = options.uniformBuffersNames;
  41246. samplersList = options.samplers;
  41247. defines = options.defines;
  41248. maxSimultaneousLights = options.maxSimultaneousLights;
  41249. }
  41250. else {
  41251. uniformsList = uniformsListOrOptions;
  41252. if (!samplersList) {
  41253. samplersList = [];
  41254. }
  41255. }
  41256. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41257. if (!defines["LIGHT" + lightIndex]) {
  41258. break;
  41259. }
  41260. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41261. if (uniformBuffersList) {
  41262. uniformBuffersList.push("Light" + lightIndex);
  41263. }
  41264. samplersList.push("shadowSampler" + lightIndex);
  41265. samplersList.push("depthSampler" + lightIndex);
  41266. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41267. samplersList.push("projectionLightSampler" + lightIndex);
  41268. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41269. }
  41270. }
  41271. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41272. uniformsList.push("morphTargetInfluences");
  41273. }
  41274. };
  41275. /**
  41276. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41277. * @param defines The defines to update while falling back
  41278. * @param fallbacks The authorized effect fallbacks
  41279. * @param maxSimultaneousLights The maximum number of lights allowed
  41280. * @param rank the current rank of the Effect
  41281. * @returns The newly affected rank
  41282. */
  41283. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41284. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41285. if (rank === void 0) { rank = 0; }
  41286. var lightFallbackRank = 0;
  41287. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41288. if (!defines["LIGHT" + lightIndex]) {
  41289. break;
  41290. }
  41291. if (lightIndex > 0) {
  41292. lightFallbackRank = rank + lightIndex;
  41293. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41294. }
  41295. if (!defines["SHADOWS"]) {
  41296. if (defines["SHADOW" + lightIndex]) {
  41297. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41298. }
  41299. if (defines["SHADOWPCF" + lightIndex]) {
  41300. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41301. }
  41302. if (defines["SHADOWPCSS" + lightIndex]) {
  41303. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41304. }
  41305. if (defines["SHADOWPOISSON" + lightIndex]) {
  41306. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41307. }
  41308. if (defines["SHADOWESM" + lightIndex]) {
  41309. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41310. }
  41311. }
  41312. }
  41313. return lightFallbackRank++;
  41314. };
  41315. /**
  41316. * Prepares the list of attributes required for morph targets according to the effect defines.
  41317. * @param attribs The current list of supported attribs
  41318. * @param mesh The mesh to prepare the morph targets attributes for
  41319. * @param defines The current Defines of the effect
  41320. */
  41321. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41322. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41323. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41324. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41325. var manager = mesh.morphTargetManager;
  41326. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41327. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41328. for (var index = 0; index < influencers; index++) {
  41329. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41330. if (normal) {
  41331. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41332. }
  41333. if (tangent) {
  41334. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41335. }
  41336. if (attribs.length > maxAttributesCount) {
  41337. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41338. }
  41339. }
  41340. }
  41341. };
  41342. /**
  41343. * Prepares the list of attributes required for bones according to the effect defines.
  41344. * @param attribs The current list of supported attribs
  41345. * @param mesh The mesh to prepare the bones attributes for
  41346. * @param defines The current Defines of the effect
  41347. * @param fallbacks The current efffect fallback strategy
  41348. */
  41349. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41350. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41351. fallbacks.addCPUSkinningFallback(0, mesh);
  41352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41354. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41355. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41356. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41357. }
  41358. }
  41359. };
  41360. /**
  41361. * Prepares the list of attributes required for instances according to the effect defines.
  41362. * @param attribs The current list of supported attribs
  41363. * @param defines The current Defines of the effect
  41364. */
  41365. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41366. if (defines["INSTANCES"]) {
  41367. attribs.push("world0");
  41368. attribs.push("world1");
  41369. attribs.push("world2");
  41370. attribs.push("world3");
  41371. }
  41372. };
  41373. /**
  41374. * Binds the light shadow information to the effect for the given mesh.
  41375. * @param light The light containing the generator
  41376. * @param scene The scene the lights belongs to
  41377. * @param mesh The mesh we are binding the information to render
  41378. * @param lightIndex The light index in the effect used to render the mesh
  41379. * @param effect The effect we are binding the data to
  41380. */
  41381. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41382. if (light.shadowEnabled && mesh.receiveShadows) {
  41383. var shadowGenerator = light.getShadowGenerator();
  41384. if (shadowGenerator) {
  41385. shadowGenerator.bindShadowLight(lightIndex, effect);
  41386. }
  41387. }
  41388. };
  41389. /**
  41390. * Binds the light information to the effect.
  41391. * @param light The light containing the generator
  41392. * @param effect The effect we are binding the data to
  41393. * @param lightIndex The light index in the effect used to render
  41394. */
  41395. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41396. light.transferToEffect(effect, lightIndex + "");
  41397. };
  41398. /**
  41399. * Binds the lights information from the scene to the effect for the given mesh.
  41400. * @param scene The scene the lights belongs to
  41401. * @param mesh The mesh we are binding the information to render
  41402. * @param effect The effect we are binding the data to
  41403. * @param defines The generated defines for the effect
  41404. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41405. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41406. */
  41407. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41408. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41409. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41410. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41411. for (var i = 0; i < len; i++) {
  41412. var light = mesh._lightSources[i];
  41413. var iAsString = i.toString();
  41414. var scaledIntensity = light.getScaledIntensity();
  41415. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41416. MaterialHelper.BindLightProperties(light, effect, i);
  41417. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41418. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41419. if (defines["SPECULARTERM"]) {
  41420. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41421. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41422. }
  41423. // Shadows
  41424. if (scene.shadowsEnabled) {
  41425. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41426. }
  41427. light._uniformBuffer.update();
  41428. }
  41429. };
  41430. /**
  41431. * Binds the fog information from the scene to the effect for the given mesh.
  41432. * @param scene The scene the lights belongs to
  41433. * @param mesh The mesh we are binding the information to render
  41434. * @param effect The effect we are binding the data to
  41435. * @param linearSpace Defines if the fog effect is applied in linear space
  41436. */
  41437. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41438. if (linearSpace === void 0) { linearSpace = false; }
  41439. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41440. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41441. // Convert fog color to linear space if used in a linear space computed shader.
  41442. if (linearSpace) {
  41443. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41444. effect.setColor3("vFogColor", this._tempFogColor);
  41445. }
  41446. else {
  41447. effect.setColor3("vFogColor", scene.fogColor);
  41448. }
  41449. }
  41450. };
  41451. /**
  41452. * Binds the bones information from the mesh to the effect.
  41453. * @param mesh The mesh we are binding the information to render
  41454. * @param effect The effect we are binding the data to
  41455. */
  41456. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41457. if (!effect || !mesh) {
  41458. return;
  41459. }
  41460. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41461. mesh.computeBonesUsingShaders = false;
  41462. }
  41463. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41464. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41465. if (matrices) {
  41466. effect.setMatrices("mBones", matrices);
  41467. }
  41468. }
  41469. };
  41470. /**
  41471. * Binds the morph targets information from the mesh to the effect.
  41472. * @param abstractMesh The mesh we are binding the information to render
  41473. * @param effect The effect we are binding the data to
  41474. */
  41475. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41476. var manager = abstractMesh.morphTargetManager;
  41477. if (!abstractMesh || !manager) {
  41478. return;
  41479. }
  41480. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41481. };
  41482. /**
  41483. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41484. * @param defines The generated defines used in the effect
  41485. * @param effect The effect we are binding the data to
  41486. * @param scene The scene we are willing to render with logarithmic scale for
  41487. */
  41488. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41489. if (defines["LOGARITHMICDEPTH"]) {
  41490. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41491. }
  41492. };
  41493. /**
  41494. * Binds the clip plane information from the scene to the effect.
  41495. * @param scene The scene the clip plane information are extracted from
  41496. * @param effect The effect we are binding the data to
  41497. */
  41498. MaterialHelper.BindClipPlane = function (effect, scene) {
  41499. if (scene.clipPlane) {
  41500. var clipPlane = scene.clipPlane;
  41501. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41502. }
  41503. if (scene.clipPlane2) {
  41504. var clipPlane = scene.clipPlane2;
  41505. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41506. }
  41507. if (scene.clipPlane3) {
  41508. var clipPlane = scene.clipPlane3;
  41509. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41510. }
  41511. if (scene.clipPlane4) {
  41512. var clipPlane = scene.clipPlane4;
  41513. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41514. }
  41515. };
  41516. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41517. return MaterialHelper;
  41518. }());
  41519. BABYLON.MaterialHelper = MaterialHelper;
  41520. })(BABYLON || (BABYLON = {}));
  41521. //# sourceMappingURL=babylon.materialHelper.js.map
  41522. var BABYLON;
  41523. (function (BABYLON) {
  41524. var PushMaterial = /** @class */ (function (_super) {
  41525. __extends(PushMaterial, _super);
  41526. function PushMaterial(name, scene) {
  41527. var _this = _super.call(this, name, scene) || this;
  41528. _this._normalMatrix = new BABYLON.Matrix();
  41529. _this.storeEffectOnSubMeshes = true;
  41530. return _this;
  41531. }
  41532. PushMaterial.prototype.getEffect = function () {
  41533. return this._activeEffect;
  41534. };
  41535. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41536. if (!mesh) {
  41537. return false;
  41538. }
  41539. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41540. return true;
  41541. }
  41542. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41543. };
  41544. /**
  41545. * Binds the given world matrix to the active effect
  41546. *
  41547. * @param world the matrix to bind
  41548. */
  41549. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41550. this._activeEffect.setMatrix("world", world);
  41551. };
  41552. /**
  41553. * Binds the given normal matrix to the active effect
  41554. *
  41555. * @param normalMatrix the matrix to bind
  41556. */
  41557. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41558. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41559. };
  41560. PushMaterial.prototype.bind = function (world, mesh) {
  41561. if (!mesh) {
  41562. return;
  41563. }
  41564. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41565. };
  41566. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41567. if (effect === void 0) { effect = null; }
  41568. _super.prototype._afterBind.call(this, mesh);
  41569. this.getScene()._cachedEffect = effect;
  41570. };
  41571. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41572. if (visibility === void 0) { visibility = 1; }
  41573. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41574. };
  41575. return PushMaterial;
  41576. }(BABYLON.Material));
  41577. BABYLON.PushMaterial = PushMaterial;
  41578. })(BABYLON || (BABYLON = {}));
  41579. //# sourceMappingURL=babylon.pushMaterial.js.map
  41580. var BABYLON;
  41581. (function (BABYLON) {
  41582. /** @hidden */
  41583. var StandardMaterialDefines = /** @class */ (function (_super) {
  41584. __extends(StandardMaterialDefines, _super);
  41585. function StandardMaterialDefines() {
  41586. var _this = _super.call(this) || this;
  41587. _this.MAINUV1 = false;
  41588. _this.MAINUV2 = false;
  41589. _this.DIFFUSE = false;
  41590. _this.DIFFUSEDIRECTUV = 0;
  41591. _this.AMBIENT = false;
  41592. _this.AMBIENTDIRECTUV = 0;
  41593. _this.OPACITY = false;
  41594. _this.OPACITYDIRECTUV = 0;
  41595. _this.OPACITYRGB = false;
  41596. _this.REFLECTION = false;
  41597. _this.EMISSIVE = false;
  41598. _this.EMISSIVEDIRECTUV = 0;
  41599. _this.SPECULAR = false;
  41600. _this.SPECULARDIRECTUV = 0;
  41601. _this.BUMP = false;
  41602. _this.BUMPDIRECTUV = 0;
  41603. _this.PARALLAX = false;
  41604. _this.PARALLAXOCCLUSION = false;
  41605. _this.SPECULAROVERALPHA = false;
  41606. _this.CLIPPLANE = false;
  41607. _this.CLIPPLANE2 = false;
  41608. _this.CLIPPLANE3 = false;
  41609. _this.CLIPPLANE4 = false;
  41610. _this.ALPHATEST = false;
  41611. _this.DEPTHPREPASS = false;
  41612. _this.ALPHAFROMDIFFUSE = false;
  41613. _this.POINTSIZE = false;
  41614. _this.FOG = false;
  41615. _this.SPECULARTERM = false;
  41616. _this.DIFFUSEFRESNEL = false;
  41617. _this.OPACITYFRESNEL = false;
  41618. _this.REFLECTIONFRESNEL = false;
  41619. _this.REFRACTIONFRESNEL = false;
  41620. _this.EMISSIVEFRESNEL = false;
  41621. _this.FRESNEL = false;
  41622. _this.NORMAL = false;
  41623. _this.UV1 = false;
  41624. _this.UV2 = false;
  41625. _this.VERTEXCOLOR = false;
  41626. _this.VERTEXALPHA = false;
  41627. _this.NUM_BONE_INFLUENCERS = 0;
  41628. _this.BonesPerMesh = 0;
  41629. _this.INSTANCES = false;
  41630. _this.GLOSSINESS = false;
  41631. _this.ROUGHNESS = false;
  41632. _this.EMISSIVEASILLUMINATION = false;
  41633. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41634. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41635. _this.LIGHTMAP = false;
  41636. _this.LIGHTMAPDIRECTUV = 0;
  41637. _this.OBJECTSPACE_NORMALMAP = false;
  41638. _this.USELIGHTMAPASSHADOWMAP = false;
  41639. _this.REFLECTIONMAP_3D = false;
  41640. _this.REFLECTIONMAP_SPHERICAL = false;
  41641. _this.REFLECTIONMAP_PLANAR = false;
  41642. _this.REFLECTIONMAP_CUBIC = false;
  41643. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41644. _this.REFLECTIONMAP_PROJECTION = false;
  41645. _this.REFLECTIONMAP_SKYBOX = false;
  41646. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41647. _this.REFLECTIONMAP_EXPLICIT = false;
  41648. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41649. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41650. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41651. _this.INVERTCUBICMAP = false;
  41652. _this.LOGARITHMICDEPTH = false;
  41653. _this.REFRACTION = false;
  41654. _this.REFRACTIONMAP_3D = false;
  41655. _this.REFLECTIONOVERALPHA = false;
  41656. _this.TWOSIDEDLIGHTING = false;
  41657. _this.SHADOWFLOAT = false;
  41658. _this.MORPHTARGETS = false;
  41659. _this.MORPHTARGETS_NORMAL = false;
  41660. _this.MORPHTARGETS_TANGENT = false;
  41661. _this.NUM_MORPH_INFLUENCERS = 0;
  41662. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41663. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41664. _this.IMAGEPROCESSING = false;
  41665. _this.VIGNETTE = false;
  41666. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41667. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41668. _this.TONEMAPPING = false;
  41669. _this.TONEMAPPING_ACES = false;
  41670. _this.CONTRAST = false;
  41671. _this.COLORCURVES = false;
  41672. _this.COLORGRADING = false;
  41673. _this.COLORGRADING3D = false;
  41674. _this.SAMPLER3DGREENDEPTH = false;
  41675. _this.SAMPLER3DBGRMAP = false;
  41676. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41677. /**
  41678. * If the reflection texture on this material is in linear color space
  41679. * @hidden
  41680. */
  41681. _this.IS_REFLECTION_LINEAR = false;
  41682. /**
  41683. * If the refraction texture on this material is in linear color space
  41684. * @hidden
  41685. */
  41686. _this.IS_REFRACTION_LINEAR = false;
  41687. _this.EXPOSURE = false;
  41688. _this.rebuild();
  41689. return _this;
  41690. }
  41691. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41692. var modes = [
  41693. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41694. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41695. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41696. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41697. ];
  41698. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41699. var mode = modes_1[_i];
  41700. this[mode] = (mode === modeToEnable);
  41701. }
  41702. };
  41703. return StandardMaterialDefines;
  41704. }(BABYLON.MaterialDefines));
  41705. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41706. var StandardMaterial = /** @class */ (function (_super) {
  41707. __extends(StandardMaterial, _super);
  41708. function StandardMaterial(name, scene) {
  41709. var _this = _super.call(this, name, scene) || this;
  41710. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41711. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41712. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41713. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41714. _this.specularPower = 64;
  41715. _this._useAlphaFromDiffuseTexture = false;
  41716. _this._useEmissiveAsIllumination = false;
  41717. _this._linkEmissiveWithDiffuse = false;
  41718. _this._useSpecularOverAlpha = false;
  41719. _this._useReflectionOverAlpha = false;
  41720. _this._disableLighting = false;
  41721. _this._useObjectSpaceNormalMap = false;
  41722. _this._useParallax = false;
  41723. _this._useParallaxOcclusion = false;
  41724. _this.parallaxScaleBias = 0.05;
  41725. _this._roughness = 0;
  41726. _this.indexOfRefraction = 0.98;
  41727. _this.invertRefractionY = true;
  41728. /**
  41729. * Defines the alpha limits in alpha test mode
  41730. */
  41731. _this.alphaCutOff = 0.4;
  41732. _this._useLightmapAsShadowmap = false;
  41733. _this._useReflectionFresnelFromSpecular = false;
  41734. _this._useGlossinessFromSpecularMapAlpha = false;
  41735. _this._maxSimultaneousLights = 4;
  41736. /**
  41737. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41738. */
  41739. _this._invertNormalMapX = false;
  41740. /**
  41741. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41742. */
  41743. _this._invertNormalMapY = false;
  41744. /**
  41745. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41746. */
  41747. _this._twoSidedLighting = false;
  41748. _this._renderTargets = new BABYLON.SmartArray(16);
  41749. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41750. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41751. // Setup the default processing configuration to the scene.
  41752. _this._attachImageProcessingConfiguration(null);
  41753. _this.getRenderTargetTextures = function () {
  41754. _this._renderTargets.reset();
  41755. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41756. _this._renderTargets.push(_this._reflectionTexture);
  41757. }
  41758. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41759. _this._renderTargets.push(_this._refractionTexture);
  41760. }
  41761. return _this._renderTargets;
  41762. };
  41763. return _this;
  41764. }
  41765. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41766. /**
  41767. * Gets the image processing configuration used either in this material.
  41768. */
  41769. get: function () {
  41770. return this._imageProcessingConfiguration;
  41771. },
  41772. /**
  41773. * Sets the Default image processing configuration used either in the this material.
  41774. *
  41775. * If sets to null, the scene one is in use.
  41776. */
  41777. set: function (value) {
  41778. this._attachImageProcessingConfiguration(value);
  41779. // Ensure the effect will be rebuilt.
  41780. this._markAllSubMeshesAsTexturesDirty();
  41781. },
  41782. enumerable: true,
  41783. configurable: true
  41784. });
  41785. /**
  41786. * Attaches a new image processing configuration to the Standard Material.
  41787. * @param configuration
  41788. */
  41789. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41790. var _this = this;
  41791. if (configuration === this._imageProcessingConfiguration) {
  41792. return;
  41793. }
  41794. // Detaches observer.
  41795. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41796. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41797. }
  41798. // Pick the scene configuration if needed.
  41799. if (!configuration) {
  41800. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41801. }
  41802. else {
  41803. this._imageProcessingConfiguration = configuration;
  41804. }
  41805. // Attaches observer.
  41806. if (this._imageProcessingConfiguration) {
  41807. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41808. _this._markAllSubMeshesAsImageProcessingDirty();
  41809. });
  41810. }
  41811. };
  41812. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41813. /**
  41814. * Gets wether the color curves effect is enabled.
  41815. */
  41816. get: function () {
  41817. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41818. },
  41819. /**
  41820. * Sets wether the color curves effect is enabled.
  41821. */
  41822. set: function (value) {
  41823. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41824. },
  41825. enumerable: true,
  41826. configurable: true
  41827. });
  41828. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41829. /**
  41830. * Gets wether the color grading effect is enabled.
  41831. */
  41832. get: function () {
  41833. return this.imageProcessingConfiguration.colorGradingEnabled;
  41834. },
  41835. /**
  41836. * Gets wether the color grading effect is enabled.
  41837. */
  41838. set: function (value) {
  41839. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41840. },
  41841. enumerable: true,
  41842. configurable: true
  41843. });
  41844. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41845. /**
  41846. * Gets wether tonemapping is enabled or not.
  41847. */
  41848. get: function () {
  41849. return this._imageProcessingConfiguration.toneMappingEnabled;
  41850. },
  41851. /**
  41852. * Sets wether tonemapping is enabled or not
  41853. */
  41854. set: function (value) {
  41855. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41856. },
  41857. enumerable: true,
  41858. configurable: true
  41859. });
  41860. ;
  41861. ;
  41862. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41863. /**
  41864. * The camera exposure used on this material.
  41865. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41866. * This corresponds to a photographic exposure.
  41867. */
  41868. get: function () {
  41869. return this._imageProcessingConfiguration.exposure;
  41870. },
  41871. /**
  41872. * The camera exposure used on this material.
  41873. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41874. * This corresponds to a photographic exposure.
  41875. */
  41876. set: function (value) {
  41877. this._imageProcessingConfiguration.exposure = value;
  41878. },
  41879. enumerable: true,
  41880. configurable: true
  41881. });
  41882. ;
  41883. ;
  41884. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41885. /**
  41886. * Gets The camera contrast used on this material.
  41887. */
  41888. get: function () {
  41889. return this._imageProcessingConfiguration.contrast;
  41890. },
  41891. /**
  41892. * Sets The camera contrast used on this material.
  41893. */
  41894. set: function (value) {
  41895. this._imageProcessingConfiguration.contrast = value;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41901. /**
  41902. * Gets the Color Grading 2D Lookup Texture.
  41903. */
  41904. get: function () {
  41905. return this._imageProcessingConfiguration.colorGradingTexture;
  41906. },
  41907. /**
  41908. * Sets the Color Grading 2D Lookup Texture.
  41909. */
  41910. set: function (value) {
  41911. this._imageProcessingConfiguration.colorGradingTexture = value;
  41912. },
  41913. enumerable: true,
  41914. configurable: true
  41915. });
  41916. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41917. /**
  41918. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41919. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41920. * 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;
  41921. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41922. */
  41923. get: function () {
  41924. return this._imageProcessingConfiguration.colorCurves;
  41925. },
  41926. /**
  41927. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41928. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41929. * 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;
  41930. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41931. */
  41932. set: function (value) {
  41933. this._imageProcessingConfiguration.colorCurves = value;
  41934. },
  41935. enumerable: true,
  41936. configurable: true
  41937. });
  41938. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41939. /**
  41940. * Gets a boolean indicating that current material needs to register RTT
  41941. */
  41942. get: function () {
  41943. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41944. return true;
  41945. }
  41946. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41947. return true;
  41948. }
  41949. return false;
  41950. },
  41951. enumerable: true,
  41952. configurable: true
  41953. });
  41954. StandardMaterial.prototype.getClassName = function () {
  41955. return "StandardMaterial";
  41956. };
  41957. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41958. get: function () {
  41959. return this._useLogarithmicDepth;
  41960. },
  41961. set: function (value) {
  41962. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41963. this._markAllSubMeshesAsMiscDirty();
  41964. },
  41965. enumerable: true,
  41966. configurable: true
  41967. });
  41968. StandardMaterial.prototype.needAlphaBlending = function () {
  41969. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41970. };
  41971. StandardMaterial.prototype.needAlphaTesting = function () {
  41972. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41973. };
  41974. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41975. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41976. };
  41977. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41978. return this._diffuseTexture;
  41979. };
  41980. /**
  41981. * Child classes can use it to update shaders
  41982. */
  41983. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41984. if (useInstances === void 0) { useInstances = false; }
  41985. if (subMesh.effect && this.isFrozen) {
  41986. if (this._wasPreviouslyReady) {
  41987. return true;
  41988. }
  41989. }
  41990. if (!subMesh._materialDefines) {
  41991. subMesh._materialDefines = new StandardMaterialDefines();
  41992. }
  41993. var scene = this.getScene();
  41994. var defines = subMesh._materialDefines;
  41995. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41996. if (defines._renderId === scene.getRenderId()) {
  41997. return true;
  41998. }
  41999. }
  42000. var engine = scene.getEngine();
  42001. // Lights
  42002. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42003. // Textures
  42004. if (defines._areTexturesDirty) {
  42005. defines._needUVs = false;
  42006. defines.MAINUV1 = false;
  42007. defines.MAINUV2 = false;
  42008. if (scene.texturesEnabled) {
  42009. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42010. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42011. return false;
  42012. }
  42013. else {
  42014. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42015. }
  42016. }
  42017. else {
  42018. defines.DIFFUSE = false;
  42019. }
  42020. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42021. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42022. return false;
  42023. }
  42024. else {
  42025. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42026. }
  42027. }
  42028. else {
  42029. defines.AMBIENT = false;
  42030. }
  42031. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42032. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42033. return false;
  42034. }
  42035. else {
  42036. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42037. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42038. }
  42039. }
  42040. else {
  42041. defines.OPACITY = false;
  42042. }
  42043. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42044. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42045. return false;
  42046. }
  42047. else {
  42048. defines._needNormals = true;
  42049. defines.REFLECTION = true;
  42050. defines.ROUGHNESS = (this._roughness > 0);
  42051. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42052. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42053. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42054. switch (this._reflectionTexture.coordinatesMode) {
  42055. case BABYLON.Texture.EXPLICIT_MODE:
  42056. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42057. break;
  42058. case BABYLON.Texture.PLANAR_MODE:
  42059. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42060. break;
  42061. case BABYLON.Texture.PROJECTION_MODE:
  42062. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42063. break;
  42064. case BABYLON.Texture.SKYBOX_MODE:
  42065. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42066. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42067. break;
  42068. case BABYLON.Texture.SPHERICAL_MODE:
  42069. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42070. break;
  42071. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42072. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42073. break;
  42074. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42075. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42076. break;
  42077. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42078. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42079. break;
  42080. case BABYLON.Texture.CUBIC_MODE:
  42081. case BABYLON.Texture.INVCUBIC_MODE:
  42082. default:
  42083. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42084. break;
  42085. }
  42086. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42087. }
  42088. }
  42089. else {
  42090. defines.REFLECTION = false;
  42091. }
  42092. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42093. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42094. return false;
  42095. }
  42096. else {
  42097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42098. }
  42099. }
  42100. else {
  42101. defines.EMISSIVE = false;
  42102. }
  42103. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42104. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42105. return false;
  42106. }
  42107. else {
  42108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42109. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42110. }
  42111. }
  42112. else {
  42113. defines.LIGHTMAP = false;
  42114. }
  42115. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42116. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42117. return false;
  42118. }
  42119. else {
  42120. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42121. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42122. }
  42123. }
  42124. else {
  42125. defines.SPECULAR = false;
  42126. }
  42127. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42128. // Bump texure can not be not blocking.
  42129. if (!this._bumpTexture.isReady()) {
  42130. return false;
  42131. }
  42132. else {
  42133. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42134. defines.PARALLAX = this._useParallax;
  42135. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42136. }
  42137. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42138. }
  42139. else {
  42140. defines.BUMP = false;
  42141. }
  42142. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42143. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42144. return false;
  42145. }
  42146. else {
  42147. defines._needUVs = true;
  42148. defines.REFRACTION = true;
  42149. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42150. }
  42151. }
  42152. else {
  42153. defines.REFRACTION = false;
  42154. }
  42155. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42156. }
  42157. else {
  42158. defines.DIFFUSE = false;
  42159. defines.AMBIENT = false;
  42160. defines.OPACITY = false;
  42161. defines.REFLECTION = false;
  42162. defines.EMISSIVE = false;
  42163. defines.LIGHTMAP = false;
  42164. defines.BUMP = false;
  42165. defines.REFRACTION = false;
  42166. }
  42167. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42168. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42169. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42170. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42171. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42172. }
  42173. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42174. if (!this._imageProcessingConfiguration.isReady()) {
  42175. return false;
  42176. }
  42177. this._imageProcessingConfiguration.prepareDefines(defines);
  42178. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42179. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42180. }
  42181. if (defines._areFresnelDirty) {
  42182. if (StandardMaterial.FresnelEnabled) {
  42183. // Fresnel
  42184. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42185. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42186. this._reflectionFresnelParameters) {
  42187. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42188. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42189. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42190. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42191. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42192. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42193. defines._needNormals = true;
  42194. defines.FRESNEL = true;
  42195. }
  42196. }
  42197. else {
  42198. defines.FRESNEL = false;
  42199. }
  42200. }
  42201. // Misc.
  42202. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42203. // Attribs
  42204. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42205. // Values that need to be evaluated on every frame
  42206. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42207. // Get correct effect
  42208. if (defines.isDirty) {
  42209. defines.markAsProcessed();
  42210. scene.resetCachedMaterial();
  42211. // Fallbacks
  42212. var fallbacks = new BABYLON.EffectFallbacks();
  42213. if (defines.REFLECTION) {
  42214. fallbacks.addFallback(0, "REFLECTION");
  42215. }
  42216. if (defines.SPECULAR) {
  42217. fallbacks.addFallback(0, "SPECULAR");
  42218. }
  42219. if (defines.BUMP) {
  42220. fallbacks.addFallback(0, "BUMP");
  42221. }
  42222. if (defines.PARALLAX) {
  42223. fallbacks.addFallback(1, "PARALLAX");
  42224. }
  42225. if (defines.PARALLAXOCCLUSION) {
  42226. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42227. }
  42228. if (defines.SPECULAROVERALPHA) {
  42229. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42230. }
  42231. if (defines.FOG) {
  42232. fallbacks.addFallback(1, "FOG");
  42233. }
  42234. if (defines.POINTSIZE) {
  42235. fallbacks.addFallback(0, "POINTSIZE");
  42236. }
  42237. if (defines.LOGARITHMICDEPTH) {
  42238. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42239. }
  42240. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42241. if (defines.SPECULARTERM) {
  42242. fallbacks.addFallback(0, "SPECULARTERM");
  42243. }
  42244. if (defines.DIFFUSEFRESNEL) {
  42245. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42246. }
  42247. if (defines.OPACITYFRESNEL) {
  42248. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42249. }
  42250. if (defines.REFLECTIONFRESNEL) {
  42251. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42252. }
  42253. if (defines.EMISSIVEFRESNEL) {
  42254. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42255. }
  42256. if (defines.FRESNEL) {
  42257. fallbacks.addFallback(4, "FRESNEL");
  42258. }
  42259. //Attributes
  42260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42261. if (defines.NORMAL) {
  42262. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42263. }
  42264. if (defines.UV1) {
  42265. attribs.push(BABYLON.VertexBuffer.UVKind);
  42266. }
  42267. if (defines.UV2) {
  42268. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42269. }
  42270. if (defines.VERTEXCOLOR) {
  42271. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42272. }
  42273. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42274. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42275. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42276. var shaderName = "default";
  42277. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42278. "vFogInfos", "vFogColor", "pointSize",
  42279. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42280. "mBones",
  42281. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42282. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42283. "vReflectionPosition", "vReflectionSize",
  42284. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42285. ];
  42286. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42287. var uniformBuffers = ["Material", "Scene"];
  42288. if (BABYLON.ImageProcessingConfiguration) {
  42289. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42290. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42291. }
  42292. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42293. uniformsNames: uniforms,
  42294. uniformBuffersNames: uniformBuffers,
  42295. samplers: samplers,
  42296. defines: defines,
  42297. maxSimultaneousLights: this._maxSimultaneousLights
  42298. });
  42299. if (this.customShaderNameResolve) {
  42300. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42301. }
  42302. var join = defines.toString();
  42303. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42304. attributes: attribs,
  42305. uniformsNames: uniforms,
  42306. uniformBuffersNames: uniformBuffers,
  42307. samplers: samplers,
  42308. defines: join,
  42309. fallbacks: fallbacks,
  42310. onCompiled: this.onCompiled,
  42311. onError: this.onError,
  42312. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42313. }, engine), defines);
  42314. this.buildUniformLayout();
  42315. }
  42316. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42317. return false;
  42318. }
  42319. defines._renderId = scene.getRenderId();
  42320. this._wasPreviouslyReady = true;
  42321. return true;
  42322. };
  42323. StandardMaterial.prototype.buildUniformLayout = function () {
  42324. // Order is important !
  42325. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42326. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42327. this._uniformBuffer.addUniform("opacityParts", 4);
  42328. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42329. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42330. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42331. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42332. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42333. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42334. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42335. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42336. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42337. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42338. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42339. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42340. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42341. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42342. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42343. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42344. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42345. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42346. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42347. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42348. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42349. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42350. this._uniformBuffer.addUniform("specularMatrix", 16);
  42351. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42352. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42353. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42354. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42355. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42356. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42357. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42358. this._uniformBuffer.addUniform("pointSize", 1);
  42359. this._uniformBuffer.create();
  42360. };
  42361. StandardMaterial.prototype.unbind = function () {
  42362. if (this._activeEffect) {
  42363. var needFlag = false;
  42364. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42365. this._activeEffect.setTexture("reflection2DSampler", null);
  42366. needFlag = true;
  42367. }
  42368. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42369. this._activeEffect.setTexture("refraction2DSampler", null);
  42370. needFlag = true;
  42371. }
  42372. if (needFlag) {
  42373. this._markAllSubMeshesAsTexturesDirty();
  42374. }
  42375. }
  42376. _super.prototype.unbind.call(this);
  42377. };
  42378. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42379. var scene = this.getScene();
  42380. var defines = subMesh._materialDefines;
  42381. if (!defines) {
  42382. return;
  42383. }
  42384. var effect = subMesh.effect;
  42385. if (!effect) {
  42386. return;
  42387. }
  42388. this._activeEffect = effect;
  42389. // Matrices
  42390. this.bindOnlyWorldMatrix(world);
  42391. // Normal Matrix
  42392. if (defines.OBJECTSPACE_NORMALMAP) {
  42393. world.toNormalMatrix(this._normalMatrix);
  42394. this.bindOnlyNormalMatrix(this._normalMatrix);
  42395. }
  42396. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42397. // Bones
  42398. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42399. if (mustRebind) {
  42400. this._uniformBuffer.bindToEffect(effect, "Material");
  42401. this.bindViewProjection(effect);
  42402. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42403. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42404. // Fresnel
  42405. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42406. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42407. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42408. }
  42409. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42410. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42411. }
  42412. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42413. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42414. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42415. }
  42416. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42417. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42418. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42419. }
  42420. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42421. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42422. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42423. }
  42424. }
  42425. // Textures
  42426. if (scene.texturesEnabled) {
  42427. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42428. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42429. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42430. if (this._diffuseTexture.hasAlpha) {
  42431. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42432. }
  42433. }
  42434. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42435. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42436. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42437. }
  42438. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42439. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42440. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42441. }
  42442. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42443. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42444. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42445. if (this._reflectionTexture.boundingBoxSize) {
  42446. var cubeTexture = this._reflectionTexture;
  42447. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42448. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42449. }
  42450. }
  42451. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42452. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42453. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42454. }
  42455. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42456. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42457. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42458. }
  42459. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42460. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42461. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42462. }
  42463. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42464. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42465. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42466. if (scene._mirroredCameraPosition) {
  42467. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42468. }
  42469. else {
  42470. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42471. }
  42472. }
  42473. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42474. var depth = 1.0;
  42475. if (!this._refractionTexture.isCube) {
  42476. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42477. if (this._refractionTexture.depth) {
  42478. depth = this._refractionTexture.depth;
  42479. }
  42480. }
  42481. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42482. }
  42483. }
  42484. // Point size
  42485. if (this.pointsCloud) {
  42486. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42487. }
  42488. if (defines.SPECULARTERM) {
  42489. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42490. }
  42491. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42492. // Diffuse
  42493. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42494. }
  42495. // Textures
  42496. if (scene.texturesEnabled) {
  42497. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42498. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42499. }
  42500. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42501. effect.setTexture("ambientSampler", this._ambientTexture);
  42502. }
  42503. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42504. effect.setTexture("opacitySampler", this._opacityTexture);
  42505. }
  42506. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42507. if (this._reflectionTexture.isCube) {
  42508. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42509. }
  42510. else {
  42511. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42512. }
  42513. }
  42514. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42515. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42516. }
  42517. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42518. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42519. }
  42520. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42521. effect.setTexture("specularSampler", this._specularTexture);
  42522. }
  42523. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42524. effect.setTexture("bumpSampler", this._bumpTexture);
  42525. }
  42526. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42527. var depth = 1.0;
  42528. if (this._refractionTexture.isCube) {
  42529. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42530. }
  42531. else {
  42532. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42533. }
  42534. }
  42535. }
  42536. // Clip plane
  42537. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42538. // Colors
  42539. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42540. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42541. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42542. }
  42543. if (mustRebind || !this.isFrozen) {
  42544. // Lights
  42545. if (scene.lightsEnabled && !this._disableLighting) {
  42546. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42547. }
  42548. // View
  42549. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42550. this.bindView(effect);
  42551. }
  42552. // Fog
  42553. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42554. // Morph targets
  42555. if (defines.NUM_MORPH_INFLUENCERS) {
  42556. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42557. }
  42558. // Log. depth
  42559. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42560. // image processing
  42561. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42562. this._imageProcessingConfiguration.bind(this._activeEffect);
  42563. }
  42564. }
  42565. this._uniformBuffer.update();
  42566. this._afterBind(mesh, this._activeEffect);
  42567. };
  42568. StandardMaterial.prototype.getAnimatables = function () {
  42569. var results = [];
  42570. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42571. results.push(this._diffuseTexture);
  42572. }
  42573. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42574. results.push(this._ambientTexture);
  42575. }
  42576. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42577. results.push(this._opacityTexture);
  42578. }
  42579. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42580. results.push(this._reflectionTexture);
  42581. }
  42582. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42583. results.push(this._emissiveTexture);
  42584. }
  42585. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42586. results.push(this._specularTexture);
  42587. }
  42588. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42589. results.push(this._bumpTexture);
  42590. }
  42591. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42592. results.push(this._lightmapTexture);
  42593. }
  42594. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42595. results.push(this._refractionTexture);
  42596. }
  42597. return results;
  42598. };
  42599. StandardMaterial.prototype.getActiveTextures = function () {
  42600. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42601. if (this._diffuseTexture) {
  42602. activeTextures.push(this._diffuseTexture);
  42603. }
  42604. if (this._ambientTexture) {
  42605. activeTextures.push(this._ambientTexture);
  42606. }
  42607. if (this._opacityTexture) {
  42608. activeTextures.push(this._opacityTexture);
  42609. }
  42610. if (this._reflectionTexture) {
  42611. activeTextures.push(this._reflectionTexture);
  42612. }
  42613. if (this._emissiveTexture) {
  42614. activeTextures.push(this._emissiveTexture);
  42615. }
  42616. if (this._specularTexture) {
  42617. activeTextures.push(this._specularTexture);
  42618. }
  42619. if (this._bumpTexture) {
  42620. activeTextures.push(this._bumpTexture);
  42621. }
  42622. if (this._lightmapTexture) {
  42623. activeTextures.push(this._lightmapTexture);
  42624. }
  42625. if (this._refractionTexture) {
  42626. activeTextures.push(this._refractionTexture);
  42627. }
  42628. return activeTextures;
  42629. };
  42630. StandardMaterial.prototype.hasTexture = function (texture) {
  42631. if (_super.prototype.hasTexture.call(this, texture)) {
  42632. return true;
  42633. }
  42634. if (this._diffuseTexture === texture) {
  42635. return true;
  42636. }
  42637. if (this._ambientTexture === texture) {
  42638. return true;
  42639. }
  42640. if (this._opacityTexture === texture) {
  42641. return true;
  42642. }
  42643. if (this._reflectionTexture === texture) {
  42644. return true;
  42645. }
  42646. if (this._emissiveTexture === texture) {
  42647. return true;
  42648. }
  42649. if (this._specularTexture === texture) {
  42650. return true;
  42651. }
  42652. if (this._bumpTexture === texture) {
  42653. return true;
  42654. }
  42655. if (this._lightmapTexture === texture) {
  42656. return true;
  42657. }
  42658. if (this._refractionTexture === texture) {
  42659. return true;
  42660. }
  42661. return false;
  42662. };
  42663. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42664. if (forceDisposeTextures) {
  42665. if (this._diffuseTexture) {
  42666. this._diffuseTexture.dispose();
  42667. }
  42668. if (this._ambientTexture) {
  42669. this._ambientTexture.dispose();
  42670. }
  42671. if (this._opacityTexture) {
  42672. this._opacityTexture.dispose();
  42673. }
  42674. if (this._reflectionTexture) {
  42675. this._reflectionTexture.dispose();
  42676. }
  42677. if (this._emissiveTexture) {
  42678. this._emissiveTexture.dispose();
  42679. }
  42680. if (this._specularTexture) {
  42681. this._specularTexture.dispose();
  42682. }
  42683. if (this._bumpTexture) {
  42684. this._bumpTexture.dispose();
  42685. }
  42686. if (this._lightmapTexture) {
  42687. this._lightmapTexture.dispose();
  42688. }
  42689. if (this._refractionTexture) {
  42690. this._refractionTexture.dispose();
  42691. }
  42692. }
  42693. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42694. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42695. }
  42696. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42697. };
  42698. StandardMaterial.prototype.clone = function (name) {
  42699. var _this = this;
  42700. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42701. result.name = name;
  42702. result.id = name;
  42703. return result;
  42704. };
  42705. StandardMaterial.prototype.serialize = function () {
  42706. return BABYLON.SerializationHelper.Serialize(this);
  42707. };
  42708. // Statics
  42709. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42710. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42711. };
  42712. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42713. get: function () {
  42714. return StandardMaterial._DiffuseTextureEnabled;
  42715. },
  42716. set: function (value) {
  42717. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42718. return;
  42719. }
  42720. StandardMaterial._DiffuseTextureEnabled = value;
  42721. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42722. },
  42723. enumerable: true,
  42724. configurable: true
  42725. });
  42726. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42727. get: function () {
  42728. return StandardMaterial._AmbientTextureEnabled;
  42729. },
  42730. set: function (value) {
  42731. if (StandardMaterial._AmbientTextureEnabled === value) {
  42732. return;
  42733. }
  42734. StandardMaterial._AmbientTextureEnabled = value;
  42735. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42741. get: function () {
  42742. return StandardMaterial._OpacityTextureEnabled;
  42743. },
  42744. set: function (value) {
  42745. if (StandardMaterial._OpacityTextureEnabled === value) {
  42746. return;
  42747. }
  42748. StandardMaterial._OpacityTextureEnabled = value;
  42749. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42750. },
  42751. enumerable: true,
  42752. configurable: true
  42753. });
  42754. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42755. get: function () {
  42756. return StandardMaterial._ReflectionTextureEnabled;
  42757. },
  42758. set: function (value) {
  42759. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42760. return;
  42761. }
  42762. StandardMaterial._ReflectionTextureEnabled = value;
  42763. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42764. },
  42765. enumerable: true,
  42766. configurable: true
  42767. });
  42768. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42769. get: function () {
  42770. return StandardMaterial._EmissiveTextureEnabled;
  42771. },
  42772. set: function (value) {
  42773. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42774. return;
  42775. }
  42776. StandardMaterial._EmissiveTextureEnabled = value;
  42777. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42778. },
  42779. enumerable: true,
  42780. configurable: true
  42781. });
  42782. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42783. get: function () {
  42784. return StandardMaterial._SpecularTextureEnabled;
  42785. },
  42786. set: function (value) {
  42787. if (StandardMaterial._SpecularTextureEnabled === value) {
  42788. return;
  42789. }
  42790. StandardMaterial._SpecularTextureEnabled = value;
  42791. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42792. },
  42793. enumerable: true,
  42794. configurable: true
  42795. });
  42796. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42797. get: function () {
  42798. return StandardMaterial._BumpTextureEnabled;
  42799. },
  42800. set: function (value) {
  42801. if (StandardMaterial._BumpTextureEnabled === value) {
  42802. return;
  42803. }
  42804. StandardMaterial._BumpTextureEnabled = value;
  42805. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42806. },
  42807. enumerable: true,
  42808. configurable: true
  42809. });
  42810. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42811. get: function () {
  42812. return StandardMaterial._LightmapTextureEnabled;
  42813. },
  42814. set: function (value) {
  42815. if (StandardMaterial._LightmapTextureEnabled === value) {
  42816. return;
  42817. }
  42818. StandardMaterial._LightmapTextureEnabled = value;
  42819. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42820. },
  42821. enumerable: true,
  42822. configurable: true
  42823. });
  42824. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42825. get: function () {
  42826. return StandardMaterial._RefractionTextureEnabled;
  42827. },
  42828. set: function (value) {
  42829. if (StandardMaterial._RefractionTextureEnabled === value) {
  42830. return;
  42831. }
  42832. StandardMaterial._RefractionTextureEnabled = value;
  42833. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42834. },
  42835. enumerable: true,
  42836. configurable: true
  42837. });
  42838. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42839. get: function () {
  42840. return StandardMaterial._ColorGradingTextureEnabled;
  42841. },
  42842. set: function (value) {
  42843. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42844. return;
  42845. }
  42846. StandardMaterial._ColorGradingTextureEnabled = value;
  42847. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42848. },
  42849. enumerable: true,
  42850. configurable: true
  42851. });
  42852. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42853. get: function () {
  42854. return StandardMaterial._FresnelEnabled;
  42855. },
  42856. set: function (value) {
  42857. if (StandardMaterial._FresnelEnabled === value) {
  42858. return;
  42859. }
  42860. StandardMaterial._FresnelEnabled = value;
  42861. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42862. },
  42863. enumerable: true,
  42864. configurable: true
  42865. });
  42866. // Flags used to enable or disable a type of texture for all Standard Materials
  42867. StandardMaterial._DiffuseTextureEnabled = true;
  42868. StandardMaterial._AmbientTextureEnabled = true;
  42869. StandardMaterial._OpacityTextureEnabled = true;
  42870. StandardMaterial._ReflectionTextureEnabled = true;
  42871. StandardMaterial._EmissiveTextureEnabled = true;
  42872. StandardMaterial._SpecularTextureEnabled = true;
  42873. StandardMaterial._BumpTextureEnabled = true;
  42874. StandardMaterial._LightmapTextureEnabled = true;
  42875. StandardMaterial._RefractionTextureEnabled = true;
  42876. StandardMaterial._ColorGradingTextureEnabled = true;
  42877. StandardMaterial._FresnelEnabled = true;
  42878. __decorate([
  42879. BABYLON.serializeAsTexture("diffuseTexture")
  42880. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42881. __decorate([
  42882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42883. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42884. __decorate([
  42885. BABYLON.serializeAsTexture("ambientTexture")
  42886. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42887. __decorate([
  42888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42889. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42890. __decorate([
  42891. BABYLON.serializeAsTexture("opacityTexture")
  42892. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42893. __decorate([
  42894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42895. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42896. __decorate([
  42897. BABYLON.serializeAsTexture("reflectionTexture")
  42898. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42899. __decorate([
  42900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42901. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42902. __decorate([
  42903. BABYLON.serializeAsTexture("emissiveTexture")
  42904. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42905. __decorate([
  42906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42907. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42908. __decorate([
  42909. BABYLON.serializeAsTexture("specularTexture")
  42910. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42911. __decorate([
  42912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42913. ], StandardMaterial.prototype, "specularTexture", void 0);
  42914. __decorate([
  42915. BABYLON.serializeAsTexture("bumpTexture")
  42916. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42917. __decorate([
  42918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42919. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42920. __decorate([
  42921. BABYLON.serializeAsTexture("lightmapTexture")
  42922. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42923. __decorate([
  42924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42925. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42926. __decorate([
  42927. BABYLON.serializeAsTexture("refractionTexture")
  42928. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42929. __decorate([
  42930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42931. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42932. __decorate([
  42933. BABYLON.serializeAsColor3("ambient")
  42934. ], StandardMaterial.prototype, "ambientColor", void 0);
  42935. __decorate([
  42936. BABYLON.serializeAsColor3("diffuse")
  42937. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42938. __decorate([
  42939. BABYLON.serializeAsColor3("specular")
  42940. ], StandardMaterial.prototype, "specularColor", void 0);
  42941. __decorate([
  42942. BABYLON.serializeAsColor3("emissive")
  42943. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42944. __decorate([
  42945. BABYLON.serialize()
  42946. ], StandardMaterial.prototype, "specularPower", void 0);
  42947. __decorate([
  42948. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42949. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42950. __decorate([
  42951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42952. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42953. __decorate([
  42954. BABYLON.serialize("useEmissiveAsIllumination")
  42955. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42956. __decorate([
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42958. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42959. __decorate([
  42960. BABYLON.serialize("linkEmissiveWithDiffuse")
  42961. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42962. __decorate([
  42963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42964. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42965. __decorate([
  42966. BABYLON.serialize("useSpecularOverAlpha")
  42967. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42968. __decorate([
  42969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42970. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42971. __decorate([
  42972. BABYLON.serialize("useReflectionOverAlpha")
  42973. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42974. __decorate([
  42975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42976. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42977. __decorate([
  42978. BABYLON.serialize("disableLighting")
  42979. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42980. __decorate([
  42981. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42982. ], StandardMaterial.prototype, "disableLighting", void 0);
  42983. __decorate([
  42984. BABYLON.serialize("useObjectSpaceNormalMap")
  42985. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42986. __decorate([
  42987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42988. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42989. __decorate([
  42990. BABYLON.serialize("useParallax")
  42991. ], StandardMaterial.prototype, "_useParallax", void 0);
  42992. __decorate([
  42993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42994. ], StandardMaterial.prototype, "useParallax", void 0);
  42995. __decorate([
  42996. BABYLON.serialize("useParallaxOcclusion")
  42997. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42998. __decorate([
  42999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43000. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43001. __decorate([
  43002. BABYLON.serialize()
  43003. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43004. __decorate([
  43005. BABYLON.serialize("roughness")
  43006. ], StandardMaterial.prototype, "_roughness", void 0);
  43007. __decorate([
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43009. ], StandardMaterial.prototype, "roughness", void 0);
  43010. __decorate([
  43011. BABYLON.serialize()
  43012. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43013. __decorate([
  43014. BABYLON.serialize()
  43015. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43016. __decorate([
  43017. BABYLON.serialize()
  43018. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43019. __decorate([
  43020. BABYLON.serialize("useLightmapAsShadowmap")
  43021. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43022. __decorate([
  43023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43024. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43025. __decorate([
  43026. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43027. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43028. __decorate([
  43029. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43030. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43031. __decorate([
  43032. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43033. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43034. __decorate([
  43035. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43036. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43037. __decorate([
  43038. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43039. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43040. __decorate([
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43042. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43043. __decorate([
  43044. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43045. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43046. __decorate([
  43047. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43048. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43049. __decorate([
  43050. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43051. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43052. __decorate([
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43054. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43055. __decorate([
  43056. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43057. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43058. __decorate([
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43060. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43061. __decorate([
  43062. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43063. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43064. __decorate([
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43067. __decorate([
  43068. BABYLON.serialize("maxSimultaneousLights")
  43069. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43070. __decorate([
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43072. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43073. __decorate([
  43074. BABYLON.serialize("invertNormalMapX")
  43075. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43076. __decorate([
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43079. __decorate([
  43080. BABYLON.serialize("invertNormalMapY")
  43081. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43082. __decorate([
  43083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43084. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43085. __decorate([
  43086. BABYLON.serialize("twoSidedLighting")
  43087. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43088. __decorate([
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43091. __decorate([
  43092. BABYLON.serialize()
  43093. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43094. return StandardMaterial;
  43095. }(BABYLON.PushMaterial));
  43096. BABYLON.StandardMaterial = StandardMaterial;
  43097. })(BABYLON || (BABYLON = {}));
  43098. //# sourceMappingURL=babylon.standardMaterial.js.map
  43099. var BABYLON;
  43100. (function (BABYLON) {
  43101. /**
  43102. * Class representing spherical polynomial coefficients to the 3rd degree
  43103. */
  43104. var SphericalPolynomial = /** @class */ (function () {
  43105. function SphericalPolynomial() {
  43106. /**
  43107. * The x coefficients of the spherical polynomial
  43108. */
  43109. this.x = BABYLON.Vector3.Zero();
  43110. /**
  43111. * The y coefficients of the spherical polynomial
  43112. */
  43113. this.y = BABYLON.Vector3.Zero();
  43114. /**
  43115. * The z coefficients of the spherical polynomial
  43116. */
  43117. this.z = BABYLON.Vector3.Zero();
  43118. /**
  43119. * The xx coefficients of the spherical polynomial
  43120. */
  43121. this.xx = BABYLON.Vector3.Zero();
  43122. /**
  43123. * The yy coefficients of the spherical polynomial
  43124. */
  43125. this.yy = BABYLON.Vector3.Zero();
  43126. /**
  43127. * The zz coefficients of the spherical polynomial
  43128. */
  43129. this.zz = BABYLON.Vector3.Zero();
  43130. /**
  43131. * The xy coefficients of the spherical polynomial
  43132. */
  43133. this.xy = BABYLON.Vector3.Zero();
  43134. /**
  43135. * The yz coefficients of the spherical polynomial
  43136. */
  43137. this.yz = BABYLON.Vector3.Zero();
  43138. /**
  43139. * The zx coefficients of the spherical polynomial
  43140. */
  43141. this.zx = BABYLON.Vector3.Zero();
  43142. }
  43143. /**
  43144. * Adds an ambient color to the spherical polynomial
  43145. * @param color the color to add
  43146. */
  43147. SphericalPolynomial.prototype.addAmbient = function (color) {
  43148. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43149. this.xx = this.xx.add(colorVector);
  43150. this.yy = this.yy.add(colorVector);
  43151. this.zz = this.zz.add(colorVector);
  43152. };
  43153. /**
  43154. * Scales the spherical polynomial by the given amount
  43155. * @param scale the amount to scale
  43156. */
  43157. SphericalPolynomial.prototype.scale = function (scale) {
  43158. this.x = this.x.scale(scale);
  43159. this.y = this.y.scale(scale);
  43160. this.z = this.z.scale(scale);
  43161. this.xx = this.xx.scale(scale);
  43162. this.yy = this.yy.scale(scale);
  43163. this.zz = this.zz.scale(scale);
  43164. this.yz = this.yz.scale(scale);
  43165. this.zx = this.zx.scale(scale);
  43166. this.xy = this.xy.scale(scale);
  43167. };
  43168. /**
  43169. * Gets the spherical polynomial from harmonics
  43170. * @param harmonics the spherical harmonics
  43171. * @returns the spherical polynomial
  43172. */
  43173. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43174. var result = new SphericalPolynomial();
  43175. result.x = harmonics.l11.scale(1.02333);
  43176. result.y = harmonics.l1_1.scale(1.02333);
  43177. result.z = harmonics.l10.scale(1.02333);
  43178. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43179. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43180. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43181. result.yz = harmonics.l2_1.scale(0.858086);
  43182. result.zx = harmonics.l21.scale(0.858086);
  43183. result.xy = harmonics.l2_2.scale(0.858086);
  43184. result.scale(1.0 / Math.PI);
  43185. return result;
  43186. };
  43187. /**
  43188. * Constructs a spherical polynomial from an array.
  43189. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43190. * @returns the spherical polynomial
  43191. */
  43192. SphericalPolynomial.FromArray = function (data) {
  43193. var sp = new SphericalPolynomial();
  43194. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43195. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43196. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43197. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43198. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43199. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43200. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43201. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43202. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43203. return sp;
  43204. };
  43205. return SphericalPolynomial;
  43206. }());
  43207. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43208. /**
  43209. * Class representing spherical harmonics coefficients to the 3rd degree
  43210. */
  43211. var SphericalHarmonics = /** @class */ (function () {
  43212. function SphericalHarmonics() {
  43213. /**
  43214. * The l0,0 coefficients of the spherical harmonics
  43215. */
  43216. this.l00 = BABYLON.Vector3.Zero();
  43217. /**
  43218. * The l1,-1 coefficients of the spherical harmonics
  43219. */
  43220. this.l1_1 = BABYLON.Vector3.Zero();
  43221. /**
  43222. * The l1,0 coefficients of the spherical harmonics
  43223. */
  43224. this.l10 = BABYLON.Vector3.Zero();
  43225. /**
  43226. * The l1,1 coefficients of the spherical harmonics
  43227. */
  43228. this.l11 = BABYLON.Vector3.Zero();
  43229. /**
  43230. * The l2,-2 coefficients of the spherical harmonics
  43231. */
  43232. this.l2_2 = BABYLON.Vector3.Zero();
  43233. /**
  43234. * The l2,-1 coefficients of the spherical harmonics
  43235. */
  43236. this.l2_1 = BABYLON.Vector3.Zero();
  43237. /**
  43238. * The l2,0 coefficients of the spherical harmonics
  43239. */
  43240. this.l20 = BABYLON.Vector3.Zero();
  43241. /**
  43242. * The l2,1 coefficients of the spherical harmonics
  43243. */
  43244. this.l21 = BABYLON.Vector3.Zero();
  43245. /**
  43246. * The l2,2 coefficients of the spherical harmonics
  43247. */
  43248. this.lL22 = BABYLON.Vector3.Zero();
  43249. }
  43250. /**
  43251. * Adds a light to the spherical harmonics
  43252. * @param direction the direction of the light
  43253. * @param color the color of the light
  43254. * @param deltaSolidAngle the delta solid angle of the light
  43255. */
  43256. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43257. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43258. var c = colorVector.scale(deltaSolidAngle);
  43259. this.l00 = this.l00.add(c.scale(0.282095));
  43260. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43261. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43262. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43263. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43264. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43265. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43266. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43267. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43268. };
  43269. /**
  43270. * Scales the spherical harmonics by the given amount
  43271. * @param scale the amount to scale
  43272. */
  43273. SphericalHarmonics.prototype.scale = function (scale) {
  43274. this.l00 = this.l00.scale(scale);
  43275. this.l1_1 = this.l1_1.scale(scale);
  43276. this.l10 = this.l10.scale(scale);
  43277. this.l11 = this.l11.scale(scale);
  43278. this.l2_2 = this.l2_2.scale(scale);
  43279. this.l2_1 = this.l2_1.scale(scale);
  43280. this.l20 = this.l20.scale(scale);
  43281. this.l21 = this.l21.scale(scale);
  43282. this.lL22 = this.lL22.scale(scale);
  43283. };
  43284. /**
  43285. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43286. *
  43287. * ```
  43288. * E_lm = A_l * L_lm
  43289. * ```
  43290. *
  43291. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43292. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43293. * the scaling factors are given in equation 9.
  43294. */
  43295. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43296. // Constant (Band 0)
  43297. this.l00 = this.l00.scale(3.141593);
  43298. // Linear (Band 1)
  43299. this.l1_1 = this.l1_1.scale(2.094395);
  43300. this.l10 = this.l10.scale(2.094395);
  43301. this.l11 = this.l11.scale(2.094395);
  43302. // Quadratic (Band 2)
  43303. this.l2_2 = this.l2_2.scale(0.785398);
  43304. this.l2_1 = this.l2_1.scale(0.785398);
  43305. this.l20 = this.l20.scale(0.785398);
  43306. this.l21 = this.l21.scale(0.785398);
  43307. this.lL22 = this.lL22.scale(0.785398);
  43308. };
  43309. /**
  43310. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43311. *
  43312. * ```
  43313. * L = (1/pi) * E * rho
  43314. * ```
  43315. *
  43316. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43317. */
  43318. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43319. this.scale(1.0 / Math.PI);
  43320. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43321. // (The pixel shader must apply albedo after texture fetches, etc).
  43322. };
  43323. /**
  43324. * Gets the spherical harmonics from polynomial
  43325. * @param polynomial the spherical polynomial
  43326. * @returns the spherical harmonics
  43327. */
  43328. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43329. var result = new SphericalHarmonics();
  43330. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43331. result.l1_1 = polynomial.y.scale(0.977204);
  43332. result.l10 = polynomial.z.scale(0.977204);
  43333. result.l11 = polynomial.x.scale(0.977204);
  43334. result.l2_2 = polynomial.xy.scale(1.16538);
  43335. result.l2_1 = polynomial.yz.scale(1.16538);
  43336. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43337. result.l21 = polynomial.zx.scale(1.16538);
  43338. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43339. result.scale(Math.PI);
  43340. return result;
  43341. };
  43342. /**
  43343. * Constructs a spherical harmonics from an array.
  43344. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43345. * @returns the spherical harmonics
  43346. */
  43347. SphericalHarmonics.FromArray = function (data) {
  43348. var sh = new SphericalHarmonics();
  43349. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43350. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43351. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43352. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43353. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43354. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43355. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43356. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43357. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43358. return sh;
  43359. };
  43360. return SphericalHarmonics;
  43361. }());
  43362. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43363. })(BABYLON || (BABYLON = {}));
  43364. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43365. var BABYLON;
  43366. (function (BABYLON) {
  43367. var FileFaceOrientation = /** @class */ (function () {
  43368. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43369. this.name = name;
  43370. this.worldAxisForNormal = worldAxisForNormal;
  43371. this.worldAxisForFileX = worldAxisForFileX;
  43372. this.worldAxisForFileY = worldAxisForFileY;
  43373. }
  43374. return FileFaceOrientation;
  43375. }());
  43376. ;
  43377. /**
  43378. * Helper class dealing with the extraction of spherical polynomial dataArray
  43379. * from a cube map.
  43380. */
  43381. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43382. function CubeMapToSphericalPolynomialTools() {
  43383. }
  43384. /**
  43385. * Converts a texture to the according Spherical Polynomial data.
  43386. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43387. *
  43388. * @param texture The texture to extract the information from.
  43389. * @return The Spherical Polynomial data.
  43390. */
  43391. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43392. if (!texture.isCube) {
  43393. // Only supports cube Textures currently.
  43394. return null;
  43395. }
  43396. var size = texture.getSize().width;
  43397. var right = texture.readPixels(0);
  43398. var left = texture.readPixels(1);
  43399. var up;
  43400. var down;
  43401. if (texture.isRenderTarget) {
  43402. up = texture.readPixels(3);
  43403. down = texture.readPixels(2);
  43404. }
  43405. else {
  43406. up = texture.readPixels(2);
  43407. down = texture.readPixels(3);
  43408. }
  43409. var front = texture.readPixels(4);
  43410. var back = texture.readPixels(5);
  43411. var gammaSpace = texture.gammaSpace;
  43412. // Always read as RGBA.
  43413. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43414. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43415. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43416. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43417. }
  43418. var cubeInfo = {
  43419. size: size,
  43420. right: right,
  43421. left: left,
  43422. up: up,
  43423. down: down,
  43424. front: front,
  43425. back: back,
  43426. format: format,
  43427. type: type,
  43428. gammaSpace: gammaSpace,
  43429. };
  43430. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43431. };
  43432. /**
  43433. * Converts a cubemap to the according Spherical Polynomial data.
  43434. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43435. *
  43436. * @param cubeInfo The Cube map to extract the information from.
  43437. * @return The Spherical Polynomial data.
  43438. */
  43439. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43440. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43441. var totalSolidAngle = 0.0;
  43442. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43443. var du = 2.0 / cubeInfo.size;
  43444. var dv = du;
  43445. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43446. var minUV = du * 0.5 - 1.0;
  43447. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43448. var fileFace = this.FileFaces[faceIndex];
  43449. var dataArray = cubeInfo[fileFace.name];
  43450. var v = minUV;
  43451. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43452. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43453. // Because SP is still linear, so summation is fine in that basis.
  43454. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43455. for (var y = 0; y < cubeInfo.size; y++) {
  43456. var u = minUV;
  43457. for (var x = 0; x < cubeInfo.size; x++) {
  43458. // World direction (not normalised)
  43459. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43460. worldDirection.normalize();
  43461. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43462. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43463. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43464. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43465. // Handle Integer types.
  43466. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43467. r /= 255;
  43468. g /= 255;
  43469. b /= 255;
  43470. }
  43471. // Handle Gamma space textures.
  43472. if (cubeInfo.gammaSpace) {
  43473. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43474. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43475. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43476. }
  43477. var color = new BABYLON.Color3(r, g, b);
  43478. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43479. totalSolidAngle += deltaSolidAngle;
  43480. u += du;
  43481. }
  43482. v += dv;
  43483. }
  43484. }
  43485. // Solid angle for entire sphere is 4*pi
  43486. var sphereSolidAngle = 4.0 * Math.PI;
  43487. // Adjust the solid angle to allow for how many faces we processed.
  43488. var facesProcessed = 6.0;
  43489. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43490. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43491. // This is needed because the numerical integration over the cube uses a
  43492. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43493. // and also to compensate for accumulative error due to float precision in the summation.
  43494. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43495. sphericalHarmonics.scale(correctionFactor);
  43496. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43497. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43498. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43499. };
  43500. CubeMapToSphericalPolynomialTools.FileFaces = [
  43501. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43502. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43503. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43504. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43505. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43506. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43507. ];
  43508. return CubeMapToSphericalPolynomialTools;
  43509. }());
  43510. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43511. })(BABYLON || (BABYLON = {}));
  43512. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43513. var BABYLON;
  43514. (function (BABYLON) {
  43515. /**
  43516. * Manages the defines for the PBR Material.
  43517. * @hiddenChildren
  43518. */
  43519. var PBRMaterialDefines = /** @class */ (function (_super) {
  43520. __extends(PBRMaterialDefines, _super);
  43521. /**
  43522. * Initializes the PBR Material defines.
  43523. */
  43524. function PBRMaterialDefines() {
  43525. var _this = _super.call(this) || this;
  43526. _this.PBR = true;
  43527. _this.MAINUV1 = false;
  43528. _this.MAINUV2 = false;
  43529. _this.UV1 = false;
  43530. _this.UV2 = false;
  43531. _this.ALBEDO = false;
  43532. _this.ALBEDODIRECTUV = 0;
  43533. _this.VERTEXCOLOR = false;
  43534. _this.AMBIENT = false;
  43535. _this.AMBIENTDIRECTUV = 0;
  43536. _this.AMBIENTINGRAYSCALE = false;
  43537. _this.OPACITY = false;
  43538. _this.VERTEXALPHA = false;
  43539. _this.OPACITYDIRECTUV = 0;
  43540. _this.OPACITYRGB = false;
  43541. _this.ALPHATEST = false;
  43542. _this.DEPTHPREPASS = false;
  43543. _this.ALPHABLEND = false;
  43544. _this.ALPHAFROMALBEDO = false;
  43545. _this.ALPHATESTVALUE = "0.5";
  43546. _this.SPECULAROVERALPHA = false;
  43547. _this.RADIANCEOVERALPHA = false;
  43548. _this.ALPHAFRESNEL = false;
  43549. _this.LINEARALPHAFRESNEL = false;
  43550. _this.PREMULTIPLYALPHA = false;
  43551. _this.EMISSIVE = false;
  43552. _this.EMISSIVEDIRECTUV = 0;
  43553. _this.REFLECTIVITY = false;
  43554. _this.REFLECTIVITYDIRECTUV = 0;
  43555. _this.SPECULARTERM = false;
  43556. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43557. _this.MICROSURFACEAUTOMATIC = false;
  43558. _this.LODBASEDMICROSFURACE = false;
  43559. _this.MICROSURFACEMAP = false;
  43560. _this.MICROSURFACEMAPDIRECTUV = 0;
  43561. _this.METALLICWORKFLOW = false;
  43562. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43563. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43564. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43565. _this.AOSTOREINMETALMAPRED = false;
  43566. _this.ENVIRONMENTBRDF = false;
  43567. _this.NORMAL = false;
  43568. _this.TANGENT = false;
  43569. _this.BUMP = false;
  43570. _this.BUMPDIRECTUV = 0;
  43571. _this.OBJECTSPACE_NORMALMAP = false;
  43572. _this.PARALLAX = false;
  43573. _this.PARALLAXOCCLUSION = false;
  43574. _this.NORMALXYSCALE = true;
  43575. _this.LIGHTMAP = false;
  43576. _this.LIGHTMAPDIRECTUV = 0;
  43577. _this.USELIGHTMAPASSHADOWMAP = false;
  43578. _this.GAMMALIGHTMAP = false;
  43579. _this.REFLECTION = false;
  43580. _this.REFLECTIONMAP_3D = false;
  43581. _this.REFLECTIONMAP_SPHERICAL = false;
  43582. _this.REFLECTIONMAP_PLANAR = false;
  43583. _this.REFLECTIONMAP_CUBIC = false;
  43584. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43585. _this.REFLECTIONMAP_PROJECTION = false;
  43586. _this.REFLECTIONMAP_SKYBOX = false;
  43587. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43588. _this.REFLECTIONMAP_EXPLICIT = false;
  43589. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43590. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43591. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43592. _this.INVERTCUBICMAP = false;
  43593. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43594. _this.USESPHERICALINVERTEX = false;
  43595. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43596. _this.LODINREFLECTIONALPHA = false;
  43597. _this.GAMMAREFLECTION = false;
  43598. _this.RGBDREFLECTION = false;
  43599. _this.RADIANCEOCCLUSION = false;
  43600. _this.HORIZONOCCLUSION = false;
  43601. _this.REFRACTION = false;
  43602. _this.REFRACTIONMAP_3D = false;
  43603. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43604. _this.LODINREFRACTIONALPHA = false;
  43605. _this.GAMMAREFRACTION = false;
  43606. _this.RGBDREFRACTION = false;
  43607. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43608. _this.INSTANCES = false;
  43609. _this.NUM_BONE_INFLUENCERS = 0;
  43610. _this.BonesPerMesh = 0;
  43611. _this.NONUNIFORMSCALING = false;
  43612. _this.MORPHTARGETS = false;
  43613. _this.MORPHTARGETS_NORMAL = false;
  43614. _this.MORPHTARGETS_TANGENT = false;
  43615. _this.NUM_MORPH_INFLUENCERS = 0;
  43616. _this.IMAGEPROCESSING = false;
  43617. _this.VIGNETTE = false;
  43618. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43619. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43620. _this.TONEMAPPING = false;
  43621. _this.TONEMAPPING_ACES = false;
  43622. _this.CONTRAST = false;
  43623. _this.COLORCURVES = false;
  43624. _this.COLORGRADING = false;
  43625. _this.COLORGRADING3D = false;
  43626. _this.SAMPLER3DGREENDEPTH = false;
  43627. _this.SAMPLER3DBGRMAP = false;
  43628. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43629. _this.EXPOSURE = false;
  43630. _this.USEPHYSICALLIGHTFALLOFF = false;
  43631. _this.USEGLTFLIGHTFALLOFF = false;
  43632. _this.TWOSIDEDLIGHTING = false;
  43633. _this.SHADOWFLOAT = false;
  43634. _this.CLIPPLANE = false;
  43635. _this.CLIPPLANE2 = false;
  43636. _this.CLIPPLANE3 = false;
  43637. _this.CLIPPLANE4 = false;
  43638. _this.POINTSIZE = false;
  43639. _this.FOG = false;
  43640. _this.LOGARITHMICDEPTH = false;
  43641. _this.FORCENORMALFORWARD = false;
  43642. _this.SPECULARAA = false;
  43643. _this.UNLIT = false;
  43644. _this.rebuild();
  43645. return _this;
  43646. }
  43647. /**
  43648. * Resets the PBR Material defines.
  43649. */
  43650. PBRMaterialDefines.prototype.reset = function () {
  43651. _super.prototype.reset.call(this);
  43652. this.ALPHATESTVALUE = "0.5";
  43653. this.PBR = true;
  43654. };
  43655. return PBRMaterialDefines;
  43656. }(BABYLON.MaterialDefines));
  43657. /**
  43658. * The Physically based material base class of BJS.
  43659. *
  43660. * This offers the main features of a standard PBR material.
  43661. * For more information, please refer to the documentation :
  43662. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43663. */
  43664. var PBRBaseMaterial = /** @class */ (function (_super) {
  43665. __extends(PBRBaseMaterial, _super);
  43666. /**
  43667. * Instantiates a new PBRMaterial instance.
  43668. *
  43669. * @param name The material name
  43670. * @param scene The scene the material will be use in.
  43671. */
  43672. function PBRBaseMaterial(name, scene) {
  43673. var _this = _super.call(this, name, scene) || this;
  43674. /**
  43675. * Intensity of the direct lights e.g. the four lights available in your scene.
  43676. * This impacts both the direct diffuse and specular highlights.
  43677. */
  43678. _this._directIntensity = 1.0;
  43679. /**
  43680. * Intensity of the emissive part of the material.
  43681. * This helps controlling the emissive effect without modifying the emissive color.
  43682. */
  43683. _this._emissiveIntensity = 1.0;
  43684. /**
  43685. * Intensity of the environment e.g. how much the environment will light the object
  43686. * either through harmonics for rough material or through the refelction for shiny ones.
  43687. */
  43688. _this._environmentIntensity = 1.0;
  43689. /**
  43690. * This is a special control allowing the reduction of the specular highlights coming from the
  43691. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43692. */
  43693. _this._specularIntensity = 1.0;
  43694. /**
  43695. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43696. */
  43697. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43698. /**
  43699. * Debug Control allowing disabling the bump map on this material.
  43700. */
  43701. _this._disableBumpMap = false;
  43702. /**
  43703. * AKA Occlusion Texture Intensity in other nomenclature.
  43704. */
  43705. _this._ambientTextureStrength = 1.0;
  43706. /**
  43707. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43708. * 1 means it completely occludes it
  43709. * 0 mean it has no impact
  43710. */
  43711. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43712. /**
  43713. * The color of a material in ambient lighting.
  43714. */
  43715. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43716. /**
  43717. * AKA Diffuse Color in other nomenclature.
  43718. */
  43719. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43720. /**
  43721. * AKA Specular Color in other nomenclature.
  43722. */
  43723. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43724. /**
  43725. * The color applied when light is reflected from a material.
  43726. */
  43727. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43728. /**
  43729. * The color applied when light is emitted from a material.
  43730. */
  43731. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43732. /**
  43733. * AKA Glossiness in other nomenclature.
  43734. */
  43735. _this._microSurface = 0.9;
  43736. /**
  43737. * source material index of refraction (IOR)' / 'destination material IOR.
  43738. */
  43739. _this._indexOfRefraction = 0.66;
  43740. /**
  43741. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43742. */
  43743. _this._invertRefractionY = false;
  43744. /**
  43745. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43746. * Materials half opaque for instance using refraction could benefit from this control.
  43747. */
  43748. _this._linkRefractionWithTransparency = false;
  43749. /**
  43750. * Specifies that the material will use the light map as a show map.
  43751. */
  43752. _this._useLightmapAsShadowmap = false;
  43753. /**
  43754. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43755. * makes the reflect vector face the model (under horizon).
  43756. */
  43757. _this._useHorizonOcclusion = true;
  43758. /**
  43759. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43760. * too much the area relying on ambient texture to define their ambient occlusion.
  43761. */
  43762. _this._useRadianceOcclusion = true;
  43763. /**
  43764. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43765. */
  43766. _this._useAlphaFromAlbedoTexture = false;
  43767. /**
  43768. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43769. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43770. */
  43771. _this._useSpecularOverAlpha = true;
  43772. /**
  43773. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43774. */
  43775. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43776. /**
  43777. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43778. */
  43779. _this._useRoughnessFromMetallicTextureAlpha = true;
  43780. /**
  43781. * Specifies if the metallic texture contains the roughness information in its green channel.
  43782. */
  43783. _this._useRoughnessFromMetallicTextureGreen = false;
  43784. /**
  43785. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43786. */
  43787. _this._useMetallnessFromMetallicTextureBlue = false;
  43788. /**
  43789. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43790. */
  43791. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43792. /**
  43793. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43794. */
  43795. _this._useAmbientInGrayScale = false;
  43796. /**
  43797. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43798. * The material will try to infer what glossiness each pixel should be.
  43799. */
  43800. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43801. /**
  43802. * Defines the falloff type used in this material.
  43803. * It by default is Physical.
  43804. */
  43805. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43806. /**
  43807. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43808. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43809. */
  43810. _this._useRadianceOverAlpha = true;
  43811. /**
  43812. * Allows using an object space normal map (instead of tangent space).
  43813. */
  43814. _this._useObjectSpaceNormalMap = false;
  43815. /**
  43816. * Allows using the bump map in parallax mode.
  43817. */
  43818. _this._useParallax = false;
  43819. /**
  43820. * Allows using the bump map in parallax occlusion mode.
  43821. */
  43822. _this._useParallaxOcclusion = false;
  43823. /**
  43824. * Controls the scale bias of the parallax mode.
  43825. */
  43826. _this._parallaxScaleBias = 0.05;
  43827. /**
  43828. * If sets to true, disables all the lights affecting the material.
  43829. */
  43830. _this._disableLighting = false;
  43831. /**
  43832. * Number of Simultaneous lights allowed on the material.
  43833. */
  43834. _this._maxSimultaneousLights = 4;
  43835. /**
  43836. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43837. */
  43838. _this._invertNormalMapX = false;
  43839. /**
  43840. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43841. */
  43842. _this._invertNormalMapY = false;
  43843. /**
  43844. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43845. */
  43846. _this._twoSidedLighting = false;
  43847. /**
  43848. * Defines the alpha limits in alpha test mode.
  43849. */
  43850. _this._alphaCutOff = 0.4;
  43851. /**
  43852. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43853. */
  43854. _this._forceAlphaTest = false;
  43855. /**
  43856. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43857. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43858. */
  43859. _this._useAlphaFresnel = false;
  43860. /**
  43861. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43862. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43863. */
  43864. _this._useLinearAlphaFresnel = false;
  43865. /**
  43866. * The transparency mode of the material.
  43867. */
  43868. _this._transparencyMode = null;
  43869. /**
  43870. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43871. * from cos thetav and roughness:
  43872. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43873. */
  43874. _this._environmentBRDFTexture = null;
  43875. /**
  43876. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43877. */
  43878. _this._forceIrradianceInFragment = false;
  43879. /**
  43880. * Force normal to face away from face.
  43881. */
  43882. _this._forceNormalForward = false;
  43883. /**
  43884. * Enables specular anti aliasing in the PBR shader.
  43885. * It will both interacts on the Geometry for analytical and IBL lighting.
  43886. * It also prefilter the roughness map based on the bump values.
  43887. */
  43888. _this._enableSpecularAntiAliasing = false;
  43889. /**
  43890. * Stores the available render targets.
  43891. */
  43892. _this._renderTargets = new BABYLON.SmartArray(16);
  43893. /**
  43894. * Sets the global ambient color for the material used in lighting calculations.
  43895. */
  43896. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43897. /**
  43898. * If set to true, no lighting calculations will be applied.
  43899. */
  43900. _this._unlit = false;
  43901. // Setup the default processing configuration to the scene.
  43902. _this._attachImageProcessingConfiguration(null);
  43903. _this.getRenderTargetTextures = function () {
  43904. _this._renderTargets.reset();
  43905. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43906. _this._renderTargets.push(_this._reflectionTexture);
  43907. }
  43908. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43909. _this._renderTargets.push(_this._refractionTexture);
  43910. }
  43911. return _this._renderTargets;
  43912. };
  43913. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43914. return _this;
  43915. }
  43916. /**
  43917. * Attaches a new image processing configuration to the PBR Material.
  43918. * @param configuration
  43919. */
  43920. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43921. var _this = this;
  43922. if (configuration === this._imageProcessingConfiguration) {
  43923. return;
  43924. }
  43925. // Detaches observer.
  43926. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43927. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43928. }
  43929. // Pick the scene configuration if needed.
  43930. if (!configuration) {
  43931. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43932. }
  43933. else {
  43934. this._imageProcessingConfiguration = configuration;
  43935. }
  43936. // Attaches observer.
  43937. if (this._imageProcessingConfiguration) {
  43938. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43939. _this._markAllSubMeshesAsImageProcessingDirty();
  43940. });
  43941. }
  43942. };
  43943. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43944. /**
  43945. * Gets a boolean indicating that current material needs to register RTT
  43946. */
  43947. get: function () {
  43948. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43949. return true;
  43950. }
  43951. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43952. return true;
  43953. }
  43954. return false;
  43955. },
  43956. enumerable: true,
  43957. configurable: true
  43958. });
  43959. /**
  43960. * Gets the name of the material class.
  43961. */
  43962. PBRBaseMaterial.prototype.getClassName = function () {
  43963. return "PBRBaseMaterial";
  43964. };
  43965. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43966. /**
  43967. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43968. */
  43969. get: function () {
  43970. return this._useLogarithmicDepth;
  43971. },
  43972. /**
  43973. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43974. */
  43975. set: function (value) {
  43976. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43977. },
  43978. enumerable: true,
  43979. configurable: true
  43980. });
  43981. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43982. /**
  43983. * Gets the current transparency mode.
  43984. */
  43985. get: function () {
  43986. return this._transparencyMode;
  43987. },
  43988. /**
  43989. * Sets the transparency mode of the material.
  43990. *
  43991. * | Value | Type | Description |
  43992. * | ----- | ----------------------------------- | ----------- |
  43993. * | 0 | OPAQUE | |
  43994. * | 1 | ALPHATEST | |
  43995. * | 2 | ALPHABLEND | |
  43996. * | 3 | ALPHATESTANDBLEND | |
  43997. *
  43998. */
  43999. set: function (value) {
  44000. if (this._transparencyMode === value) {
  44001. return;
  44002. }
  44003. this._transparencyMode = value;
  44004. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44005. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44006. },
  44007. enumerable: true,
  44008. configurable: true
  44009. });
  44010. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44011. /**
  44012. * Returns true if alpha blending should be disabled.
  44013. */
  44014. get: function () {
  44015. return (this._linkRefractionWithTransparency ||
  44016. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44017. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44018. },
  44019. enumerable: true,
  44020. configurable: true
  44021. });
  44022. /**
  44023. * Specifies whether or not this material should be rendered in alpha blend mode.
  44024. */
  44025. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44026. if (this._disableAlphaBlending) {
  44027. return false;
  44028. }
  44029. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44030. };
  44031. /**
  44032. * Specifies if the mesh will require alpha blending.
  44033. * @param mesh - BJS mesh.
  44034. */
  44035. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44036. if (this._disableAlphaBlending) {
  44037. return false;
  44038. }
  44039. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44040. };
  44041. /**
  44042. * Specifies whether or not this material should be rendered in alpha test mode.
  44043. */
  44044. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44045. if (this._forceAlphaTest) {
  44046. return true;
  44047. }
  44048. if (this._linkRefractionWithTransparency) {
  44049. return false;
  44050. }
  44051. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44052. };
  44053. /**
  44054. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44055. */
  44056. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44057. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44058. };
  44059. /**
  44060. * Gets the texture used for the alpha test.
  44061. */
  44062. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44063. return this._albedoTexture;
  44064. };
  44065. /**
  44066. * Specifies that the submesh is ready to be used.
  44067. * @param mesh - BJS mesh.
  44068. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44069. * @param useInstances - Specifies that instances should be used.
  44070. * @returns - boolean indicating that the submesh is ready or not.
  44071. */
  44072. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44073. if (subMesh.effect && this.isFrozen) {
  44074. if (this._wasPreviouslyReady) {
  44075. return true;
  44076. }
  44077. }
  44078. if (!subMesh._materialDefines) {
  44079. subMesh._materialDefines = new PBRMaterialDefines();
  44080. }
  44081. var defines = subMesh._materialDefines;
  44082. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44083. if (defines._renderId === this.getScene().getRenderId()) {
  44084. return true;
  44085. }
  44086. }
  44087. var scene = this.getScene();
  44088. var engine = scene.getEngine();
  44089. if (defines._areTexturesDirty) {
  44090. if (scene.texturesEnabled) {
  44091. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44092. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44093. return false;
  44094. }
  44095. }
  44096. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44097. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44098. return false;
  44099. }
  44100. }
  44101. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44102. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44103. return false;
  44104. }
  44105. }
  44106. var reflectionTexture = this._getReflectionTexture();
  44107. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44108. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44109. return false;
  44110. }
  44111. }
  44112. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44113. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44114. return false;
  44115. }
  44116. }
  44117. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44118. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44119. return false;
  44120. }
  44121. }
  44122. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44123. if (this._metallicTexture) {
  44124. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44125. return false;
  44126. }
  44127. }
  44128. else if (this._reflectivityTexture) {
  44129. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44130. return false;
  44131. }
  44132. }
  44133. if (this._microSurfaceTexture) {
  44134. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44135. return false;
  44136. }
  44137. }
  44138. }
  44139. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44140. // Bump texture cannot be not blocking.
  44141. if (!this._bumpTexture.isReady()) {
  44142. return false;
  44143. }
  44144. }
  44145. var refractionTexture = this._getRefractionTexture();
  44146. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44147. if (!refractionTexture.isReadyOrNotBlocking()) {
  44148. return false;
  44149. }
  44150. }
  44151. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44152. // This is blocking.
  44153. if (!this._environmentBRDFTexture.isReady()) {
  44154. return false;
  44155. }
  44156. }
  44157. }
  44158. }
  44159. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44160. if (!this._imageProcessingConfiguration.isReady()) {
  44161. return false;
  44162. }
  44163. }
  44164. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44165. mesh.createNormals(true);
  44166. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44167. }
  44168. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44169. if (effect) {
  44170. scene.resetCachedMaterial();
  44171. subMesh.setEffect(effect, defines);
  44172. this.buildUniformLayout();
  44173. }
  44174. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44175. return false;
  44176. }
  44177. defines._renderId = scene.getRenderId();
  44178. this._wasPreviouslyReady = true;
  44179. return true;
  44180. };
  44181. /**
  44182. * Specifies if the material uses metallic roughness workflow.
  44183. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44184. */
  44185. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44186. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44187. return true;
  44188. }
  44189. return false;
  44190. };
  44191. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44192. if (onCompiled === void 0) { onCompiled = null; }
  44193. if (onError === void 0) { onError = null; }
  44194. if (useInstances === void 0) { useInstances = null; }
  44195. if (useClipPlane === void 0) { useClipPlane = null; }
  44196. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44197. if (!defines.isDirty) {
  44198. return null;
  44199. }
  44200. defines.markAsProcessed();
  44201. var scene = this.getScene();
  44202. var engine = scene.getEngine();
  44203. // Fallbacks
  44204. var fallbacks = new BABYLON.EffectFallbacks();
  44205. var fallbackRank = 0;
  44206. if (defines.USESPHERICALINVERTEX) {
  44207. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44208. }
  44209. if (defines.FOG) {
  44210. fallbacks.addFallback(fallbackRank, "FOG");
  44211. }
  44212. if (defines.SPECULARAA) {
  44213. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44214. }
  44215. if (defines.POINTSIZE) {
  44216. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44217. }
  44218. if (defines.LOGARITHMICDEPTH) {
  44219. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44220. }
  44221. if (defines.PARALLAX) {
  44222. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44223. }
  44224. if (defines.PARALLAXOCCLUSION) {
  44225. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44226. }
  44227. if (defines.ENVIRONMENTBRDF) {
  44228. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44229. }
  44230. if (defines.TANGENT) {
  44231. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44232. }
  44233. if (defines.BUMP) {
  44234. fallbacks.addFallback(fallbackRank++, "BUMP");
  44235. }
  44236. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44237. if (defines.SPECULARTERM) {
  44238. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44239. }
  44240. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44241. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44242. }
  44243. if (defines.LIGHTMAP) {
  44244. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44245. }
  44246. if (defines.NORMAL) {
  44247. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44248. }
  44249. if (defines.AMBIENT) {
  44250. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44251. }
  44252. if (defines.EMISSIVE) {
  44253. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44254. }
  44255. if (defines.VERTEXCOLOR) {
  44256. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44257. }
  44258. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44259. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44260. }
  44261. if (defines.MORPHTARGETS) {
  44262. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44263. }
  44264. //Attributes
  44265. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44266. if (defines.NORMAL) {
  44267. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44268. }
  44269. if (defines.TANGENT) {
  44270. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44271. }
  44272. if (defines.UV1) {
  44273. attribs.push(BABYLON.VertexBuffer.UVKind);
  44274. }
  44275. if (defines.UV2) {
  44276. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44277. }
  44278. if (defines.VERTEXCOLOR) {
  44279. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44280. }
  44281. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44282. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44283. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44284. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44285. "vFogInfos", "vFogColor", "pointSize",
  44286. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44287. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44288. "mBones",
  44289. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44290. "vLightingIntensity",
  44291. "logarithmicDepthConstant",
  44292. "vSphericalX", "vSphericalY", "vSphericalZ",
  44293. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44294. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44295. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44296. "vTangentSpaceParams"
  44297. ];
  44298. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44299. "bumpSampler", "lightmapSampler", "opacitySampler",
  44300. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44301. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44302. "microSurfaceSampler", "environmentBrdfSampler"];
  44303. var uniformBuffers = ["Material", "Scene"];
  44304. if (BABYLON.ImageProcessingConfiguration) {
  44305. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44306. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44307. }
  44308. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44309. uniformsNames: uniforms,
  44310. uniformBuffersNames: uniformBuffers,
  44311. samplers: samplers,
  44312. defines: defines,
  44313. maxSimultaneousLights: this._maxSimultaneousLights
  44314. });
  44315. var join = defines.toString();
  44316. return engine.createEffect("pbr", {
  44317. attributes: attribs,
  44318. uniformsNames: uniforms,
  44319. uniformBuffersNames: uniformBuffers,
  44320. samplers: samplers,
  44321. defines: join,
  44322. fallbacks: fallbacks,
  44323. onCompiled: onCompiled,
  44324. onError: onError,
  44325. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44326. }, engine);
  44327. };
  44328. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44329. if (useInstances === void 0) { useInstances = null; }
  44330. if (useClipPlane === void 0) { useClipPlane = null; }
  44331. var scene = this.getScene();
  44332. var engine = scene.getEngine();
  44333. // Lights
  44334. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44335. defines._needNormals = true;
  44336. // Textures
  44337. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44338. if (defines._areTexturesDirty) {
  44339. defines._needUVs = false;
  44340. if (scene.texturesEnabled) {
  44341. if (scene.getEngine().getCaps().textureLOD) {
  44342. defines.LODBASEDMICROSFURACE = true;
  44343. }
  44344. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44345. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44346. }
  44347. else {
  44348. defines.ALBEDO = false;
  44349. }
  44350. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44352. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44353. }
  44354. else {
  44355. defines.AMBIENT = false;
  44356. }
  44357. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44358. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44359. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44360. }
  44361. else {
  44362. defines.OPACITY = false;
  44363. }
  44364. var reflectionTexture = this._getReflectionTexture();
  44365. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44366. defines.REFLECTION = true;
  44367. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44368. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44369. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44370. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44371. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44372. defines.INVERTCUBICMAP = true;
  44373. }
  44374. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44375. switch (reflectionTexture.coordinatesMode) {
  44376. case BABYLON.Texture.EXPLICIT_MODE:
  44377. defines.REFLECTIONMAP_EXPLICIT = true;
  44378. break;
  44379. case BABYLON.Texture.PLANAR_MODE:
  44380. defines.REFLECTIONMAP_PLANAR = true;
  44381. break;
  44382. case BABYLON.Texture.PROJECTION_MODE:
  44383. defines.REFLECTIONMAP_PROJECTION = true;
  44384. break;
  44385. case BABYLON.Texture.SKYBOX_MODE:
  44386. defines.REFLECTIONMAP_SKYBOX = true;
  44387. break;
  44388. case BABYLON.Texture.SPHERICAL_MODE:
  44389. defines.REFLECTIONMAP_SPHERICAL = true;
  44390. break;
  44391. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44392. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44393. break;
  44394. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44395. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44396. break;
  44397. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44398. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44399. break;
  44400. case BABYLON.Texture.CUBIC_MODE:
  44401. case BABYLON.Texture.INVCUBIC_MODE:
  44402. default:
  44403. defines.REFLECTIONMAP_CUBIC = true;
  44404. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44405. break;
  44406. }
  44407. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44408. if (reflectionTexture.sphericalPolynomial) {
  44409. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44410. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44411. defines.USESPHERICALINVERTEX = false;
  44412. }
  44413. else {
  44414. defines.USESPHERICALINVERTEX = true;
  44415. }
  44416. }
  44417. }
  44418. else {
  44419. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44420. }
  44421. }
  44422. else {
  44423. defines.REFLECTION = false;
  44424. defines.REFLECTIONMAP_3D = false;
  44425. defines.REFLECTIONMAP_SPHERICAL = false;
  44426. defines.REFLECTIONMAP_PLANAR = false;
  44427. defines.REFLECTIONMAP_CUBIC = false;
  44428. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44429. defines.REFLECTIONMAP_PROJECTION = false;
  44430. defines.REFLECTIONMAP_SKYBOX = false;
  44431. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44432. defines.REFLECTIONMAP_EXPLICIT = false;
  44433. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44434. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44435. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44436. defines.INVERTCUBICMAP = false;
  44437. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44438. defines.USESPHERICALINVERTEX = false;
  44439. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44440. defines.LODINREFLECTIONALPHA = false;
  44441. defines.GAMMAREFLECTION = false;
  44442. defines.RGBDREFLECTION = false;
  44443. }
  44444. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44445. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44446. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44447. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44448. }
  44449. else {
  44450. defines.LIGHTMAP = false;
  44451. }
  44452. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44453. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44454. }
  44455. else {
  44456. defines.EMISSIVE = false;
  44457. }
  44458. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44459. if (this._metallicTexture) {
  44460. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44461. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44462. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44463. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44464. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44465. }
  44466. else if (this._reflectivityTexture) {
  44467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44468. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44469. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44470. }
  44471. else {
  44472. defines.REFLECTIVITY = false;
  44473. }
  44474. if (this._microSurfaceTexture) {
  44475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44476. }
  44477. else {
  44478. defines.MICROSURFACEMAP = false;
  44479. }
  44480. }
  44481. else {
  44482. defines.REFLECTIVITY = false;
  44483. defines.MICROSURFACEMAP = false;
  44484. }
  44485. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44487. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44488. defines.PARALLAX = true;
  44489. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44490. }
  44491. else {
  44492. defines.PARALLAX = false;
  44493. }
  44494. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44495. }
  44496. else {
  44497. defines.BUMP = false;
  44498. }
  44499. var refractionTexture = this._getRefractionTexture();
  44500. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44501. defines.REFRACTION = true;
  44502. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44503. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44504. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44505. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44506. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44507. if (this._linkRefractionWithTransparency) {
  44508. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44509. }
  44510. }
  44511. else {
  44512. defines.REFRACTION = false;
  44513. }
  44514. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44515. defines.ENVIRONMENTBRDF = true;
  44516. }
  44517. else {
  44518. defines.ENVIRONMENTBRDF = false;
  44519. }
  44520. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44521. defines.ALPHAFROMALBEDO = true;
  44522. }
  44523. else {
  44524. defines.ALPHAFROMALBEDO = false;
  44525. }
  44526. }
  44527. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44528. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44529. defines.USEPHYSICALLIGHTFALLOFF = false;
  44530. defines.USEGLTFLIGHTFALLOFF = false;
  44531. }
  44532. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44533. defines.USEPHYSICALLIGHTFALLOFF = false;
  44534. defines.USEGLTFLIGHTFALLOFF = true;
  44535. }
  44536. else {
  44537. defines.USEPHYSICALLIGHTFALLOFF = true;
  44538. defines.USEGLTFLIGHTFALLOFF = false;
  44539. }
  44540. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44541. if (!this.backFaceCulling && this._twoSidedLighting) {
  44542. defines.TWOSIDEDLIGHTING = true;
  44543. }
  44544. else {
  44545. defines.TWOSIDEDLIGHTING = false;
  44546. }
  44547. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44548. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44549. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44550. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44551. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44552. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44553. }
  44554. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44555. this._imageProcessingConfiguration.prepareDefines(defines);
  44556. }
  44557. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44558. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44559. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44560. // Misc.
  44561. if (defines._areMiscDirty) {
  44562. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44563. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44564. }
  44565. // Values that need to be evaluated on every frame
  44566. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44567. // Attribs
  44568. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44569. };
  44570. /**
  44571. * Force shader compilation
  44572. */
  44573. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44574. var _this = this;
  44575. var localOptions = __assign({ clipPlane: false }, options);
  44576. var defines = new PBRMaterialDefines();
  44577. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44578. if (effect.isReady()) {
  44579. if (onCompiled) {
  44580. onCompiled(this);
  44581. }
  44582. }
  44583. else {
  44584. effect.onCompileObservable.add(function () {
  44585. if (onCompiled) {
  44586. onCompiled(_this);
  44587. }
  44588. });
  44589. }
  44590. };
  44591. /**
  44592. * Initializes the uniform buffer layout for the shader.
  44593. */
  44594. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44595. // Order is important !
  44596. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44597. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44598. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44599. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44600. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44601. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44602. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44603. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44604. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44605. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44606. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44607. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44608. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44609. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44610. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44611. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44612. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44613. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44614. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44615. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44616. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44617. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44618. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44619. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44620. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44621. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44622. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44623. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44624. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44625. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44626. this._uniformBuffer.addUniform("pointSize", 1);
  44627. this._uniformBuffer.create();
  44628. };
  44629. /**
  44630. * Unbinds the textures.
  44631. */
  44632. PBRBaseMaterial.prototype.unbind = function () {
  44633. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44634. this._uniformBuffer.setTexture("reflectionSampler", null);
  44635. }
  44636. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44637. this._uniformBuffer.setTexture("refractionSampler", null);
  44638. }
  44639. _super.prototype.unbind.call(this);
  44640. };
  44641. /**
  44642. * Binds the submesh data.
  44643. * @param world - The world matrix.
  44644. * @param mesh - The BJS mesh.
  44645. * @param subMesh - A submesh of the BJS mesh.
  44646. */
  44647. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44648. var scene = this.getScene();
  44649. var defines = subMesh._materialDefines;
  44650. if (!defines) {
  44651. return;
  44652. }
  44653. var effect = subMesh.effect;
  44654. if (!effect) {
  44655. return;
  44656. }
  44657. this._activeEffect = effect;
  44658. // Matrices
  44659. this.bindOnlyWorldMatrix(world);
  44660. // Normal Matrix
  44661. if (defines.OBJECTSPACE_NORMALMAP) {
  44662. world.toNormalMatrix(this._normalMatrix);
  44663. this.bindOnlyNormalMatrix(this._normalMatrix);
  44664. }
  44665. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44666. // Bones
  44667. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44668. var reflectionTexture = null;
  44669. if (mustRebind) {
  44670. this._uniformBuffer.bindToEffect(effect, "Material");
  44671. this.bindViewProjection(effect);
  44672. reflectionTexture = this._getReflectionTexture();
  44673. var refractionTexture = this._getRefractionTexture();
  44674. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44675. // Texture uniforms
  44676. if (scene.texturesEnabled) {
  44677. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44678. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44679. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44680. }
  44681. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44682. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44683. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44684. }
  44685. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44686. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44687. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44688. }
  44689. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44690. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44691. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44692. if (reflectionTexture.boundingBoxSize) {
  44693. var cubeTexture = reflectionTexture;
  44694. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44695. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44696. }
  44697. var polynomials = reflectionTexture.sphericalPolynomial;
  44698. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44699. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44700. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44701. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44702. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44703. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44704. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44705. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44706. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44707. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44708. }
  44709. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44710. }
  44711. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44712. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44713. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44714. }
  44715. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44716. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44717. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44718. }
  44719. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44720. if (this._metallicTexture) {
  44721. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44722. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44723. }
  44724. else if (this._reflectivityTexture) {
  44725. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44726. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44727. }
  44728. if (this._microSurfaceTexture) {
  44729. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44730. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44731. }
  44732. }
  44733. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44734. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44735. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44736. if (scene._mirroredCameraPosition) {
  44737. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44738. }
  44739. else {
  44740. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44741. }
  44742. }
  44743. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44744. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44745. var depth = 1.0;
  44746. if (!refractionTexture.isCube) {
  44747. if (refractionTexture.depth) {
  44748. depth = refractionTexture.depth;
  44749. }
  44750. }
  44751. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44752. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44753. }
  44754. }
  44755. // Point size
  44756. if (this.pointsCloud) {
  44757. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44758. }
  44759. // Colors
  44760. if (defines.METALLICWORKFLOW) {
  44761. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44762. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44763. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44764. }
  44765. else {
  44766. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44767. }
  44768. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44769. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44770. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44771. // Misc
  44772. this._lightingInfos.x = this._directIntensity;
  44773. this._lightingInfos.y = this._emissiveIntensity;
  44774. this._lightingInfos.z = this._environmentIntensity;
  44775. this._lightingInfos.w = this._specularIntensity;
  44776. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44777. }
  44778. // Textures
  44779. if (scene.texturesEnabled) {
  44780. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44781. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44782. }
  44783. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44784. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44785. }
  44786. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44787. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44788. }
  44789. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44790. if (defines.LODBASEDMICROSFURACE) {
  44791. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44792. }
  44793. else {
  44794. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44795. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44796. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44797. }
  44798. }
  44799. if (defines.ENVIRONMENTBRDF) {
  44800. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44801. }
  44802. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44803. if (defines.LODBASEDMICROSFURACE) {
  44804. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44805. }
  44806. else {
  44807. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44808. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44809. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44810. }
  44811. }
  44812. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44813. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44814. }
  44815. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44816. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44817. }
  44818. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44819. if (this._metallicTexture) {
  44820. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44821. }
  44822. else if (this._reflectivityTexture) {
  44823. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44824. }
  44825. if (this._microSurfaceTexture) {
  44826. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44827. }
  44828. }
  44829. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44830. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44831. }
  44832. }
  44833. // Clip plane
  44834. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44835. // Colors
  44836. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44837. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44838. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44839. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44840. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44841. }
  44842. if (mustRebind || !this.isFrozen) {
  44843. // Lights
  44844. if (scene.lightsEnabled && !this._disableLighting) {
  44845. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44846. }
  44847. // View
  44848. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44849. this.bindView(effect);
  44850. }
  44851. // Fog
  44852. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  44853. // Morph targets
  44854. if (defines.NUM_MORPH_INFLUENCERS) {
  44855. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44856. }
  44857. // image processing
  44858. this._imageProcessingConfiguration.bind(this._activeEffect);
  44859. // Log. depth
  44860. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44861. }
  44862. this._uniformBuffer.update();
  44863. this._afterBind(mesh, this._activeEffect);
  44864. };
  44865. /**
  44866. * Returns the animatable textures.
  44867. * @returns - Array of animatable textures.
  44868. */
  44869. PBRBaseMaterial.prototype.getAnimatables = function () {
  44870. var results = [];
  44871. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44872. results.push(this._albedoTexture);
  44873. }
  44874. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44875. results.push(this._ambientTexture);
  44876. }
  44877. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44878. results.push(this._opacityTexture);
  44879. }
  44880. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44881. results.push(this._reflectionTexture);
  44882. }
  44883. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44884. results.push(this._emissiveTexture);
  44885. }
  44886. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44887. results.push(this._metallicTexture);
  44888. }
  44889. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44890. results.push(this._reflectivityTexture);
  44891. }
  44892. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44893. results.push(this._bumpTexture);
  44894. }
  44895. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44896. results.push(this._lightmapTexture);
  44897. }
  44898. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44899. results.push(this._refractionTexture);
  44900. }
  44901. return results;
  44902. };
  44903. /**
  44904. * Returns the texture used for reflections.
  44905. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44906. */
  44907. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44908. if (this._reflectionTexture) {
  44909. return this._reflectionTexture;
  44910. }
  44911. return this.getScene().environmentTexture;
  44912. };
  44913. /**
  44914. * Returns the texture used for refraction or null if none is used.
  44915. * @returns - Refection texture if present. If no refraction texture and refraction
  44916. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44917. */
  44918. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44919. if (this._refractionTexture) {
  44920. return this._refractionTexture;
  44921. }
  44922. if (this._linkRefractionWithTransparency) {
  44923. return this.getScene().environmentTexture;
  44924. }
  44925. return null;
  44926. };
  44927. /**
  44928. * Disposes the resources of the material.
  44929. * @param forceDisposeEffect - Forces the disposal of effects.
  44930. * @param forceDisposeTextures - Forces the disposal of all textures.
  44931. */
  44932. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44933. if (forceDisposeTextures) {
  44934. if (this._albedoTexture) {
  44935. this._albedoTexture.dispose();
  44936. }
  44937. if (this._ambientTexture) {
  44938. this._ambientTexture.dispose();
  44939. }
  44940. if (this._opacityTexture) {
  44941. this._opacityTexture.dispose();
  44942. }
  44943. if (this._reflectionTexture) {
  44944. this._reflectionTexture.dispose();
  44945. }
  44946. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44947. this._environmentBRDFTexture.dispose();
  44948. }
  44949. if (this._emissiveTexture) {
  44950. this._emissiveTexture.dispose();
  44951. }
  44952. if (this._metallicTexture) {
  44953. this._metallicTexture.dispose();
  44954. }
  44955. if (this._reflectivityTexture) {
  44956. this._reflectivityTexture.dispose();
  44957. }
  44958. if (this._bumpTexture) {
  44959. this._bumpTexture.dispose();
  44960. }
  44961. if (this._lightmapTexture) {
  44962. this._lightmapTexture.dispose();
  44963. }
  44964. if (this._refractionTexture) {
  44965. this._refractionTexture.dispose();
  44966. }
  44967. }
  44968. this._renderTargets.dispose();
  44969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44971. }
  44972. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44973. };
  44974. /**
  44975. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44976. */
  44977. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44978. /**
  44979. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44980. * to enhance interoperability with other engines.
  44981. */
  44982. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44983. /**
  44984. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44985. * to enhance interoperability with other materials.
  44986. */
  44987. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44988. /**
  44989. * Stores the reflectivity values based on metallic roughness workflow.
  44990. */
  44991. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44992. __decorate([
  44993. BABYLON.serializeAsImageProcessingConfiguration()
  44994. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44995. __decorate([
  44996. BABYLON.serialize()
  44997. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44998. __decorate([
  44999. BABYLON.serialize()
  45000. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45001. return PBRBaseMaterial;
  45002. }(BABYLON.PushMaterial));
  45003. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45004. })(BABYLON || (BABYLON = {}));
  45005. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45006. var BABYLON;
  45007. (function (BABYLON) {
  45008. /**
  45009. * The Physically based simple base material of BJS.
  45010. *
  45011. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45012. * It is used as the base class for both the specGloss and metalRough conventions.
  45013. */
  45014. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45015. __extends(PBRBaseSimpleMaterial, _super);
  45016. /**
  45017. * Instantiates a new PBRMaterial instance.
  45018. *
  45019. * @param name The material name
  45020. * @param scene The scene the material will be use in.
  45021. */
  45022. function PBRBaseSimpleMaterial(name, scene) {
  45023. var _this = _super.call(this, name, scene) || this;
  45024. /**
  45025. * Number of Simultaneous lights allowed on the material.
  45026. */
  45027. _this.maxSimultaneousLights = 4;
  45028. /**
  45029. * If sets to true, disables all the lights affecting the material.
  45030. */
  45031. _this.disableLighting = false;
  45032. /**
  45033. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45034. */
  45035. _this.invertNormalMapX = false;
  45036. /**
  45037. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45038. */
  45039. _this.invertNormalMapY = false;
  45040. /**
  45041. * Emissivie color used to self-illuminate the model.
  45042. */
  45043. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45044. /**
  45045. * Occlusion Channel Strenght.
  45046. */
  45047. _this.occlusionStrength = 1.0;
  45048. _this.useLightmapAsShadowmap = false;
  45049. _this._useAlphaFromAlbedoTexture = true;
  45050. _this._useAmbientInGrayScale = true;
  45051. return _this;
  45052. }
  45053. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45054. /**
  45055. * Gets the current double sided mode.
  45056. */
  45057. get: function () {
  45058. return this._twoSidedLighting;
  45059. },
  45060. /**
  45061. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45062. */
  45063. set: function (value) {
  45064. if (this._twoSidedLighting === value) {
  45065. return;
  45066. }
  45067. this._twoSidedLighting = value;
  45068. this.backFaceCulling = !value;
  45069. this._markAllSubMeshesAsTexturesDirty();
  45070. },
  45071. enumerable: true,
  45072. configurable: true
  45073. });
  45074. /**
  45075. * Return the active textures of the material.
  45076. */
  45077. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45078. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45079. if (this.environmentTexture) {
  45080. activeTextures.push(this.environmentTexture);
  45081. }
  45082. if (this.normalTexture) {
  45083. activeTextures.push(this.normalTexture);
  45084. }
  45085. if (this.emissiveTexture) {
  45086. activeTextures.push(this.emissiveTexture);
  45087. }
  45088. if (this.occlusionTexture) {
  45089. activeTextures.push(this.occlusionTexture);
  45090. }
  45091. if (this.lightmapTexture) {
  45092. activeTextures.push(this.lightmapTexture);
  45093. }
  45094. return activeTextures;
  45095. };
  45096. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45097. if (_super.prototype.hasTexture.call(this, texture)) {
  45098. return true;
  45099. }
  45100. if (this.lightmapTexture === texture) {
  45101. return true;
  45102. }
  45103. return false;
  45104. };
  45105. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45106. return "PBRBaseSimpleMaterial";
  45107. };
  45108. __decorate([
  45109. BABYLON.serialize(),
  45110. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45111. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45112. __decorate([
  45113. BABYLON.serialize(),
  45114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45115. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45116. __decorate([
  45117. BABYLON.serializeAsTexture(),
  45118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45119. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45120. __decorate([
  45121. BABYLON.serialize(),
  45122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45123. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45124. __decorate([
  45125. BABYLON.serialize(),
  45126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45127. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45128. __decorate([
  45129. BABYLON.serializeAsTexture(),
  45130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45131. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45132. __decorate([
  45133. BABYLON.serializeAsColor3("emissive"),
  45134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45135. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45136. __decorate([
  45137. BABYLON.serializeAsTexture(),
  45138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45139. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45140. __decorate([
  45141. BABYLON.serialize(),
  45142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45143. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45144. __decorate([
  45145. BABYLON.serializeAsTexture(),
  45146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45147. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45148. __decorate([
  45149. BABYLON.serialize(),
  45150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45151. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45152. __decorate([
  45153. BABYLON.serialize()
  45154. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45155. __decorate([
  45156. BABYLON.serializeAsTexture(),
  45157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45158. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45159. __decorate([
  45160. BABYLON.serialize(),
  45161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45162. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45163. return PBRBaseSimpleMaterial;
  45164. }(BABYLON.PBRBaseMaterial));
  45165. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45166. })(BABYLON || (BABYLON = {}));
  45167. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45168. var BABYLON;
  45169. (function (BABYLON) {
  45170. /**
  45171. * The Physically based material of BJS.
  45172. *
  45173. * This offers the main features of a standard PBR material.
  45174. * For more information, please refer to the documentation :
  45175. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45176. */
  45177. var PBRMaterial = /** @class */ (function (_super) {
  45178. __extends(PBRMaterial, _super);
  45179. /**
  45180. * Instantiates a new PBRMaterial instance.
  45181. *
  45182. * @param name The material name
  45183. * @param scene The scene the material will be use in.
  45184. */
  45185. function PBRMaterial(name, scene) {
  45186. var _this = _super.call(this, name, scene) || this;
  45187. /**
  45188. * Intensity of the direct lights e.g. the four lights available in your scene.
  45189. * This impacts both the direct diffuse and specular highlights.
  45190. */
  45191. _this.directIntensity = 1.0;
  45192. /**
  45193. * Intensity of the emissive part of the material.
  45194. * This helps controlling the emissive effect without modifying the emissive color.
  45195. */
  45196. _this.emissiveIntensity = 1.0;
  45197. /**
  45198. * Intensity of the environment e.g. how much the environment will light the object
  45199. * either through harmonics for rough material or through the refelction for shiny ones.
  45200. */
  45201. _this.environmentIntensity = 1.0;
  45202. /**
  45203. * This is a special control allowing the reduction of the specular highlights coming from the
  45204. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45205. */
  45206. _this.specularIntensity = 1.0;
  45207. /**
  45208. * Debug Control allowing disabling the bump map on this material.
  45209. */
  45210. _this.disableBumpMap = false;
  45211. /**
  45212. * AKA Occlusion Texture Intensity in other nomenclature.
  45213. */
  45214. _this.ambientTextureStrength = 1.0;
  45215. /**
  45216. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45217. * 1 means it completely occludes it
  45218. * 0 mean it has no impact
  45219. */
  45220. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45221. /**
  45222. * The color of a material in ambient lighting.
  45223. */
  45224. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45225. /**
  45226. * AKA Diffuse Color in other nomenclature.
  45227. */
  45228. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45229. /**
  45230. * AKA Specular Color in other nomenclature.
  45231. */
  45232. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45233. /**
  45234. * The color reflected from the material.
  45235. */
  45236. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45237. /**
  45238. * The color emitted from the material.
  45239. */
  45240. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45241. /**
  45242. * AKA Glossiness in other nomenclature.
  45243. */
  45244. _this.microSurface = 1.0;
  45245. /**
  45246. * source material index of refraction (IOR)' / 'destination material IOR.
  45247. */
  45248. _this.indexOfRefraction = 0.66;
  45249. /**
  45250. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45251. */
  45252. _this.invertRefractionY = false;
  45253. /**
  45254. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45255. * Materials half opaque for instance using refraction could benefit from this control.
  45256. */
  45257. _this.linkRefractionWithTransparency = false;
  45258. _this.useLightmapAsShadowmap = false;
  45259. /**
  45260. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45261. */
  45262. _this.useAlphaFromAlbedoTexture = false;
  45263. /**
  45264. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45265. */
  45266. _this.forceAlphaTest = false;
  45267. /**
  45268. * Defines the alpha limits in alpha test mode.
  45269. */
  45270. _this.alphaCutOff = 0.4;
  45271. /**
  45272. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45273. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45274. */
  45275. _this.useSpecularOverAlpha = true;
  45276. /**
  45277. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45278. */
  45279. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45280. /**
  45281. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45282. */
  45283. _this.useRoughnessFromMetallicTextureAlpha = true;
  45284. /**
  45285. * Specifies if the metallic texture contains the roughness information in its green channel.
  45286. */
  45287. _this.useRoughnessFromMetallicTextureGreen = false;
  45288. /**
  45289. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45290. */
  45291. _this.useMetallnessFromMetallicTextureBlue = false;
  45292. /**
  45293. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45294. */
  45295. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45296. /**
  45297. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45298. */
  45299. _this.useAmbientInGrayScale = false;
  45300. /**
  45301. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45302. * The material will try to infer what glossiness each pixel should be.
  45303. */
  45304. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45305. /**
  45306. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45307. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45308. */
  45309. _this.useRadianceOverAlpha = true;
  45310. /**
  45311. * Allows using an object space normal map (instead of tangent space).
  45312. */
  45313. _this.useObjectSpaceNormalMap = false;
  45314. /**
  45315. * Allows using the bump map in parallax mode.
  45316. */
  45317. _this.useParallax = false;
  45318. /**
  45319. * Allows using the bump map in parallax occlusion mode.
  45320. */
  45321. _this.useParallaxOcclusion = false;
  45322. /**
  45323. * Controls the scale bias of the parallax mode.
  45324. */
  45325. _this.parallaxScaleBias = 0.05;
  45326. /**
  45327. * If sets to true, disables all the lights affecting the material.
  45328. */
  45329. _this.disableLighting = false;
  45330. /**
  45331. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45332. */
  45333. _this.forceIrradianceInFragment = false;
  45334. /**
  45335. * Number of Simultaneous lights allowed on the material.
  45336. */
  45337. _this.maxSimultaneousLights = 4;
  45338. /**
  45339. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45340. */
  45341. _this.invertNormalMapX = false;
  45342. /**
  45343. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45344. */
  45345. _this.invertNormalMapY = false;
  45346. /**
  45347. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45348. */
  45349. _this.twoSidedLighting = false;
  45350. /**
  45351. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45352. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45353. */
  45354. _this.useAlphaFresnel = false;
  45355. /**
  45356. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45357. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45358. */
  45359. _this.useLinearAlphaFresnel = false;
  45360. /**
  45361. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45362. * And/Or occlude the blended part.
  45363. */
  45364. _this.environmentBRDFTexture = null;
  45365. /**
  45366. * Force normal to face away from face.
  45367. */
  45368. _this.forceNormalForward = false;
  45369. /**
  45370. * Enables specular anti aliasing in the PBR shader.
  45371. * It will both interacts on the Geometry for analytical and IBL lighting.
  45372. * It also prefilter the roughness map based on the bump values.
  45373. */
  45374. _this.enableSpecularAntiAliasing = false;
  45375. /**
  45376. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45377. * makes the reflect vector face the model (under horizon).
  45378. */
  45379. _this.useHorizonOcclusion = true;
  45380. /**
  45381. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45382. * too much the area relying on ambient texture to define their ambient occlusion.
  45383. */
  45384. _this.useRadianceOcclusion = true;
  45385. /**
  45386. * If set to true, no lighting calculations will be applied.
  45387. */
  45388. _this.unlit = false;
  45389. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45390. return _this;
  45391. }
  45392. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45393. /**
  45394. * BJS is using an harcoded light falloff based on a manually sets up range.
  45395. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45396. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45397. */
  45398. get: function () {
  45399. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45400. },
  45401. /**
  45402. * BJS is using an harcoded light falloff based on a manually sets up range.
  45403. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45404. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45405. */
  45406. set: function (value) {
  45407. if (value !== this.usePhysicalLightFalloff) {
  45408. // Ensure the effect will be rebuilt.
  45409. this._markAllSubMeshesAsTexturesDirty();
  45410. if (value) {
  45411. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45412. }
  45413. else {
  45414. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45415. }
  45416. }
  45417. },
  45418. enumerable: true,
  45419. configurable: true
  45420. });
  45421. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45422. /**
  45423. * In order to support the falloff compatibility with gltf, a special mode has been added
  45424. * to reproduce the gltf light falloff.
  45425. */
  45426. get: function () {
  45427. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45428. },
  45429. /**
  45430. * In order to support the falloff compatibility with gltf, a special mode has been added
  45431. * to reproduce the gltf light falloff.
  45432. */
  45433. set: function (value) {
  45434. if (value !== this.useGLTFLightFalloff) {
  45435. // Ensure the effect will be rebuilt.
  45436. this._markAllSubMeshesAsTexturesDirty();
  45437. if (value) {
  45438. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45439. }
  45440. else {
  45441. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45442. }
  45443. }
  45444. },
  45445. enumerable: true,
  45446. configurable: true
  45447. });
  45448. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45449. /**
  45450. * Gets the image processing configuration used either in this material.
  45451. */
  45452. get: function () {
  45453. return this._imageProcessingConfiguration;
  45454. },
  45455. /**
  45456. * Sets the Default image processing configuration used either in the this material.
  45457. *
  45458. * If sets to null, the scene one is in use.
  45459. */
  45460. set: function (value) {
  45461. this._attachImageProcessingConfiguration(value);
  45462. // Ensure the effect will be rebuilt.
  45463. this._markAllSubMeshesAsTexturesDirty();
  45464. },
  45465. enumerable: true,
  45466. configurable: true
  45467. });
  45468. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45469. /**
  45470. * Gets wether the color curves effect is enabled.
  45471. */
  45472. get: function () {
  45473. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45474. },
  45475. /**
  45476. * Sets wether the color curves effect is enabled.
  45477. */
  45478. set: function (value) {
  45479. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45480. },
  45481. enumerable: true,
  45482. configurable: true
  45483. });
  45484. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45485. /**
  45486. * Gets wether the color grading effect is enabled.
  45487. */
  45488. get: function () {
  45489. return this.imageProcessingConfiguration.colorGradingEnabled;
  45490. },
  45491. /**
  45492. * Gets wether the color grading effect is enabled.
  45493. */
  45494. set: function (value) {
  45495. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45496. },
  45497. enumerable: true,
  45498. configurable: true
  45499. });
  45500. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45501. /**
  45502. * Gets wether tonemapping is enabled or not.
  45503. */
  45504. get: function () {
  45505. return this._imageProcessingConfiguration.toneMappingEnabled;
  45506. },
  45507. /**
  45508. * Sets wether tonemapping is enabled or not
  45509. */
  45510. set: function (value) {
  45511. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45512. },
  45513. enumerable: true,
  45514. configurable: true
  45515. });
  45516. ;
  45517. ;
  45518. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45519. /**
  45520. * The camera exposure used on this material.
  45521. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45522. * This corresponds to a photographic exposure.
  45523. */
  45524. get: function () {
  45525. return this._imageProcessingConfiguration.exposure;
  45526. },
  45527. /**
  45528. * The camera exposure used on this material.
  45529. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45530. * This corresponds to a photographic exposure.
  45531. */
  45532. set: function (value) {
  45533. this._imageProcessingConfiguration.exposure = value;
  45534. },
  45535. enumerable: true,
  45536. configurable: true
  45537. });
  45538. ;
  45539. ;
  45540. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45541. /**
  45542. * Gets The camera contrast used on this material.
  45543. */
  45544. get: function () {
  45545. return this._imageProcessingConfiguration.contrast;
  45546. },
  45547. /**
  45548. * Sets The camera contrast used on this material.
  45549. */
  45550. set: function (value) {
  45551. this._imageProcessingConfiguration.contrast = value;
  45552. },
  45553. enumerable: true,
  45554. configurable: true
  45555. });
  45556. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45557. /**
  45558. * Gets the Color Grading 2D Lookup Texture.
  45559. */
  45560. get: function () {
  45561. return this._imageProcessingConfiguration.colorGradingTexture;
  45562. },
  45563. /**
  45564. * Sets the Color Grading 2D Lookup Texture.
  45565. */
  45566. set: function (value) {
  45567. this._imageProcessingConfiguration.colorGradingTexture = value;
  45568. },
  45569. enumerable: true,
  45570. configurable: true
  45571. });
  45572. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45573. /**
  45574. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45575. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45576. * 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;
  45577. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45578. */
  45579. get: function () {
  45580. return this._imageProcessingConfiguration.colorCurves;
  45581. },
  45582. /**
  45583. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45584. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45585. * 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;
  45586. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45587. */
  45588. set: function (value) {
  45589. this._imageProcessingConfiguration.colorCurves = value;
  45590. },
  45591. enumerable: true,
  45592. configurable: true
  45593. });
  45594. /**
  45595. * Returns the name of this material class.
  45596. */
  45597. PBRMaterial.prototype.getClassName = function () {
  45598. return "PBRMaterial";
  45599. };
  45600. /**
  45601. * Returns an array of the actively used textures.
  45602. * @returns - Array of BaseTextures
  45603. */
  45604. PBRMaterial.prototype.getActiveTextures = function () {
  45605. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45606. if (this._albedoTexture) {
  45607. activeTextures.push(this._albedoTexture);
  45608. }
  45609. if (this._ambientTexture) {
  45610. activeTextures.push(this._ambientTexture);
  45611. }
  45612. if (this._opacityTexture) {
  45613. activeTextures.push(this._opacityTexture);
  45614. }
  45615. if (this._reflectionTexture) {
  45616. activeTextures.push(this._reflectionTexture);
  45617. }
  45618. if (this._emissiveTexture) {
  45619. activeTextures.push(this._emissiveTexture);
  45620. }
  45621. if (this._reflectivityTexture) {
  45622. activeTextures.push(this._reflectivityTexture);
  45623. }
  45624. if (this._metallicTexture) {
  45625. activeTextures.push(this._metallicTexture);
  45626. }
  45627. if (this._microSurfaceTexture) {
  45628. activeTextures.push(this._microSurfaceTexture);
  45629. }
  45630. if (this._bumpTexture) {
  45631. activeTextures.push(this._bumpTexture);
  45632. }
  45633. if (this._lightmapTexture) {
  45634. activeTextures.push(this._lightmapTexture);
  45635. }
  45636. if (this._refractionTexture) {
  45637. activeTextures.push(this._refractionTexture);
  45638. }
  45639. return activeTextures;
  45640. };
  45641. /**
  45642. * Checks to see if a texture is used in the material.
  45643. * @param texture - Base texture to use.
  45644. * @returns - Boolean specifying if a texture is used in the material.
  45645. */
  45646. PBRMaterial.prototype.hasTexture = function (texture) {
  45647. if (_super.prototype.hasTexture.call(this, texture)) {
  45648. return true;
  45649. }
  45650. if (this._albedoTexture === texture) {
  45651. return true;
  45652. }
  45653. if (this._ambientTexture === texture) {
  45654. return true;
  45655. }
  45656. if (this._opacityTexture === texture) {
  45657. return true;
  45658. }
  45659. if (this._reflectionTexture === texture) {
  45660. return true;
  45661. }
  45662. if (this._reflectivityTexture === texture) {
  45663. return true;
  45664. }
  45665. if (this._metallicTexture === texture) {
  45666. return true;
  45667. }
  45668. if (this._microSurfaceTexture === texture) {
  45669. return true;
  45670. }
  45671. if (this._bumpTexture === texture) {
  45672. return true;
  45673. }
  45674. if (this._lightmapTexture === texture) {
  45675. return true;
  45676. }
  45677. if (this._refractionTexture === texture) {
  45678. return true;
  45679. }
  45680. return false;
  45681. };
  45682. /**
  45683. * Makes a duplicate of the current material.
  45684. * @param name - name to use for the new material.
  45685. */
  45686. PBRMaterial.prototype.clone = function (name) {
  45687. var _this = this;
  45688. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45689. clone.id = name;
  45690. clone.name = name;
  45691. return clone;
  45692. };
  45693. /**
  45694. * Serializes this PBR Material.
  45695. * @returns - An object with the serialized material.
  45696. */
  45697. PBRMaterial.prototype.serialize = function () {
  45698. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45699. serializationObject.customType = "BABYLON.PBRMaterial";
  45700. return serializationObject;
  45701. };
  45702. // Statics
  45703. /**
  45704. * Parses a PBR Material from a serialized object.
  45705. * @param source - Serialized object.
  45706. * @param scene - BJS scene instance.
  45707. * @param rootUrl - url for the scene object
  45708. * @returns - PBRMaterial
  45709. */
  45710. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45711. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45712. };
  45713. /**
  45714. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45715. */
  45716. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45717. /**
  45718. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45719. */
  45720. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45721. /**
  45722. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45723. */
  45724. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45725. /**
  45726. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45727. * They are also discarded below the alpha cutoff threshold to improve performances.
  45728. */
  45729. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45730. /**
  45731. * Defines the default value of how much AO map is occluding the analytical lights
  45732. * (point spot...).
  45733. */
  45734. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45735. __decorate([
  45736. BABYLON.serialize(),
  45737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45738. ], PBRMaterial.prototype, "directIntensity", void 0);
  45739. __decorate([
  45740. BABYLON.serialize(),
  45741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45742. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45743. __decorate([
  45744. BABYLON.serialize(),
  45745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45746. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45747. __decorate([
  45748. BABYLON.serialize(),
  45749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45750. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45751. __decorate([
  45752. BABYLON.serialize(),
  45753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45754. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45755. __decorate([
  45756. BABYLON.serializeAsTexture(),
  45757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45758. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45759. __decorate([
  45760. BABYLON.serializeAsTexture(),
  45761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45762. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45763. __decorate([
  45764. BABYLON.serialize(),
  45765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45766. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45767. __decorate([
  45768. BABYLON.serialize(),
  45769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45770. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45771. __decorate([
  45772. BABYLON.serializeAsTexture(),
  45773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45774. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45775. __decorate([
  45776. BABYLON.serializeAsTexture(),
  45777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45778. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45779. __decorate([
  45780. BABYLON.serializeAsTexture(),
  45781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45782. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45783. __decorate([
  45784. BABYLON.serializeAsTexture(),
  45785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45786. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45787. __decorate([
  45788. BABYLON.serializeAsTexture(),
  45789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45790. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45791. __decorate([
  45792. BABYLON.serialize(),
  45793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45794. ], PBRMaterial.prototype, "metallic", void 0);
  45795. __decorate([
  45796. BABYLON.serialize(),
  45797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45798. ], PBRMaterial.prototype, "roughness", void 0);
  45799. __decorate([
  45800. BABYLON.serializeAsTexture(),
  45801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45802. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45803. __decorate([
  45804. BABYLON.serializeAsTexture(),
  45805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45806. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45807. __decorate([
  45808. BABYLON.serializeAsTexture(),
  45809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45810. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45811. __decorate([
  45812. BABYLON.serializeAsTexture(),
  45813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45814. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45815. __decorate([
  45816. BABYLON.serializeAsColor3("ambient"),
  45817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45818. ], PBRMaterial.prototype, "ambientColor", void 0);
  45819. __decorate([
  45820. BABYLON.serializeAsColor3("albedo"),
  45821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45822. ], PBRMaterial.prototype, "albedoColor", void 0);
  45823. __decorate([
  45824. BABYLON.serializeAsColor3("reflectivity"),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45826. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45827. __decorate([
  45828. BABYLON.serializeAsColor3("reflection"),
  45829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45830. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45831. __decorate([
  45832. BABYLON.serializeAsColor3("emissive"),
  45833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45834. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45835. __decorate([
  45836. BABYLON.serialize(),
  45837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45838. ], PBRMaterial.prototype, "microSurface", void 0);
  45839. __decorate([
  45840. BABYLON.serialize(),
  45841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45842. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45843. __decorate([
  45844. BABYLON.serialize(),
  45845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45846. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45847. __decorate([
  45848. BABYLON.serialize(),
  45849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45850. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45851. __decorate([
  45852. BABYLON.serialize(),
  45853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45854. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45855. __decorate([
  45856. BABYLON.serialize(),
  45857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45858. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45859. __decorate([
  45860. BABYLON.serialize(),
  45861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45862. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45863. __decorate([
  45864. BABYLON.serialize(),
  45865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45866. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45867. __decorate([
  45868. BABYLON.serialize(),
  45869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45870. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45871. __decorate([
  45872. BABYLON.serialize(),
  45873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45874. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45875. __decorate([
  45876. BABYLON.serialize(),
  45877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45878. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45879. __decorate([
  45880. BABYLON.serialize(),
  45881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45882. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45883. __decorate([
  45884. BABYLON.serialize(),
  45885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45886. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45887. __decorate([
  45888. BABYLON.serialize(),
  45889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45890. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45891. __decorate([
  45892. BABYLON.serialize(),
  45893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45894. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45895. __decorate([
  45896. BABYLON.serialize(),
  45897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45898. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45899. __decorate([
  45900. BABYLON.serialize()
  45901. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45902. __decorate([
  45903. BABYLON.serialize()
  45904. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45905. __decorate([
  45906. BABYLON.serialize(),
  45907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45908. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45909. __decorate([
  45910. BABYLON.serialize(),
  45911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45912. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45913. __decorate([
  45914. BABYLON.serialize(),
  45915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45916. ], PBRMaterial.prototype, "useParallax", void 0);
  45917. __decorate([
  45918. BABYLON.serialize(),
  45919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45920. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45921. __decorate([
  45922. BABYLON.serialize(),
  45923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45924. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45925. __decorate([
  45926. BABYLON.serialize(),
  45927. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45928. ], PBRMaterial.prototype, "disableLighting", void 0);
  45929. __decorate([
  45930. BABYLON.serialize(),
  45931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45932. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45933. __decorate([
  45934. BABYLON.serialize(),
  45935. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45936. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45937. __decorate([
  45938. BABYLON.serialize(),
  45939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45940. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45941. __decorate([
  45942. BABYLON.serialize(),
  45943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45944. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45945. __decorate([
  45946. BABYLON.serialize(),
  45947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45948. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45949. __decorate([
  45950. BABYLON.serialize(),
  45951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45952. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45953. __decorate([
  45954. BABYLON.serialize(),
  45955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45956. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45957. __decorate([
  45958. BABYLON.serializeAsTexture(),
  45959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45960. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45961. __decorate([
  45962. BABYLON.serialize(),
  45963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45964. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45965. __decorate([
  45966. BABYLON.serialize(),
  45967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45968. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45969. __decorate([
  45970. BABYLON.serialize(),
  45971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45972. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45973. __decorate([
  45974. BABYLON.serialize(),
  45975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45976. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45977. __decorate([
  45978. BABYLON.serialize(),
  45979. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45980. ], PBRMaterial.prototype, "unlit", void 0);
  45981. return PBRMaterial;
  45982. }(BABYLON.PBRBaseMaterial));
  45983. BABYLON.PBRMaterial = PBRMaterial;
  45984. })(BABYLON || (BABYLON = {}));
  45985. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45986. var BABYLON;
  45987. (function (BABYLON) {
  45988. /**
  45989. * The PBR material of BJS following the metal roughness convention.
  45990. *
  45991. * This fits to the PBR convention in the GLTF definition:
  45992. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45993. */
  45994. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45995. __extends(PBRMetallicRoughnessMaterial, _super);
  45996. /**
  45997. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45998. *
  45999. * @param name The material name
  46000. * @param scene The scene the material will be use in.
  46001. */
  46002. function PBRMetallicRoughnessMaterial(name, scene) {
  46003. var _this = _super.call(this, name, scene) || this;
  46004. _this._useRoughnessFromMetallicTextureAlpha = false;
  46005. _this._useRoughnessFromMetallicTextureGreen = true;
  46006. _this._useMetallnessFromMetallicTextureBlue = true;
  46007. _this.metallic = 1.0;
  46008. _this.roughness = 1.0;
  46009. return _this;
  46010. }
  46011. /**
  46012. * Return the currrent class name of the material.
  46013. */
  46014. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46015. return "PBRMetallicRoughnessMaterial";
  46016. };
  46017. /**
  46018. * Return the active textures of the material.
  46019. */
  46020. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46021. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46022. if (this.baseTexture) {
  46023. activeTextures.push(this.baseTexture);
  46024. }
  46025. if (this.metallicRoughnessTexture) {
  46026. activeTextures.push(this.metallicRoughnessTexture);
  46027. }
  46028. return activeTextures;
  46029. };
  46030. /**
  46031. * Checks to see if a texture is used in the material.
  46032. * @param texture - Base texture to use.
  46033. * @returns - Boolean specifying if a texture is used in the material.
  46034. */
  46035. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46036. if (_super.prototype.hasTexture.call(this, texture)) {
  46037. return true;
  46038. }
  46039. if (this.baseTexture === texture) {
  46040. return true;
  46041. }
  46042. if (this.metallicRoughnessTexture === texture) {
  46043. return true;
  46044. }
  46045. return false;
  46046. };
  46047. /**
  46048. * Makes a duplicate of the current material.
  46049. * @param name - name to use for the new material.
  46050. */
  46051. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46052. var _this = this;
  46053. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46054. clone.id = name;
  46055. clone.name = name;
  46056. return clone;
  46057. };
  46058. /**
  46059. * Serialize the material to a parsable JSON object.
  46060. */
  46061. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46062. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46063. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46064. return serializationObject;
  46065. };
  46066. /**
  46067. * Parses a JSON object correponding to the serialize function.
  46068. */
  46069. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46070. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46071. };
  46072. __decorate([
  46073. BABYLON.serializeAsColor3(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46075. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46076. __decorate([
  46077. BABYLON.serializeAsTexture(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46079. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46080. __decorate([
  46081. BABYLON.serialize(),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46083. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46084. __decorate([
  46085. BABYLON.serialize(),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46087. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46088. __decorate([
  46089. BABYLON.serializeAsTexture(),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46091. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46092. return PBRMetallicRoughnessMaterial;
  46093. }(BABYLON.PBRBaseSimpleMaterial));
  46094. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46095. })(BABYLON || (BABYLON = {}));
  46096. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46097. var BABYLON;
  46098. (function (BABYLON) {
  46099. /**
  46100. * The PBR material of BJS following the specular glossiness convention.
  46101. *
  46102. * This fits to the PBR convention in the GLTF definition:
  46103. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46104. */
  46105. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46106. __extends(PBRSpecularGlossinessMaterial, _super);
  46107. /**
  46108. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46109. *
  46110. * @param name The material name
  46111. * @param scene The scene the material will be use in.
  46112. */
  46113. function PBRSpecularGlossinessMaterial(name, scene) {
  46114. var _this = _super.call(this, name, scene) || this;
  46115. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46116. return _this;
  46117. }
  46118. /**
  46119. * Return the currrent class name of the material.
  46120. */
  46121. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46122. return "PBRSpecularGlossinessMaterial";
  46123. };
  46124. /**
  46125. * Return the active textures of the material.
  46126. */
  46127. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46128. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46129. if (this.diffuseTexture) {
  46130. activeTextures.push(this.diffuseTexture);
  46131. }
  46132. if (this.specularGlossinessTexture) {
  46133. activeTextures.push(this.specularGlossinessTexture);
  46134. }
  46135. return activeTextures;
  46136. };
  46137. /**
  46138. * Checks to see if a texture is used in the material.
  46139. * @param texture - Base texture to use.
  46140. * @returns - Boolean specifying if a texture is used in the material.
  46141. */
  46142. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46143. if (_super.prototype.hasTexture.call(this, texture)) {
  46144. return true;
  46145. }
  46146. if (this.diffuseTexture === texture) {
  46147. return true;
  46148. }
  46149. if (this.specularGlossinessTexture === texture) {
  46150. return true;
  46151. }
  46152. return false;
  46153. };
  46154. /**
  46155. * Makes a duplicate of the current material.
  46156. * @param name - name to use for the new material.
  46157. */
  46158. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46159. var _this = this;
  46160. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46161. clone.id = name;
  46162. clone.name = name;
  46163. return clone;
  46164. };
  46165. /**
  46166. * Serialize the material to a parsable JSON object.
  46167. */
  46168. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46169. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46170. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46171. return serializationObject;
  46172. };
  46173. /**
  46174. * Parses a JSON object correponding to the serialize function.
  46175. */
  46176. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46177. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46178. };
  46179. __decorate([
  46180. BABYLON.serializeAsColor3("diffuse"),
  46181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46182. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46183. __decorate([
  46184. BABYLON.serializeAsTexture(),
  46185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46186. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46187. __decorate([
  46188. BABYLON.serializeAsColor3("specular"),
  46189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46190. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46191. __decorate([
  46192. BABYLON.serialize(),
  46193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46194. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46195. __decorate([
  46196. BABYLON.serializeAsTexture(),
  46197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46198. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46199. return PBRSpecularGlossinessMaterial;
  46200. }(BABYLON.PBRBaseSimpleMaterial));
  46201. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46202. })(BABYLON || (BABYLON = {}));
  46203. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46204. var BABYLON;
  46205. (function (BABYLON) {
  46206. /**
  46207. * This is a list of all the different input types that are available in the application.
  46208. * Fo instance: ArcRotateCameraGamepadInput...
  46209. */
  46210. BABYLON.CameraInputTypes = {};
  46211. /**
  46212. * This represents the input manager used within a camera.
  46213. * It helps dealing with all the different kind of input attached to a camera.
  46214. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46215. */
  46216. var CameraInputsManager = /** @class */ (function () {
  46217. /**
  46218. * Instantiate a new Camera Input Manager.
  46219. * @param camera Defines the camera the input manager blongs to
  46220. */
  46221. function CameraInputsManager(camera) {
  46222. this.attached = {};
  46223. this.camera = camera;
  46224. this.checkInputs = function () { };
  46225. }
  46226. /**
  46227. * Add an input method to a camera
  46228. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46229. * @param input camera input method
  46230. */
  46231. CameraInputsManager.prototype.add = function (input) {
  46232. var type = input.getSimpleName();
  46233. if (this.attached[type]) {
  46234. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46235. return;
  46236. }
  46237. this.attached[type] = input;
  46238. input.camera = this.camera;
  46239. //for checkInputs, we are dynamically creating a function
  46240. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46241. if (input.checkInputs) {
  46242. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46243. }
  46244. if (this.attachedElement) {
  46245. input.attachControl(this.attachedElement);
  46246. }
  46247. };
  46248. /**
  46249. * Remove a specific input method from a camera
  46250. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46251. * @param inputToRemove camera input method
  46252. */
  46253. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46254. for (var cam in this.attached) {
  46255. var input = this.attached[cam];
  46256. if (input === inputToRemove) {
  46257. input.detachControl(this.attachedElement);
  46258. input.camera = null;
  46259. delete this.attached[cam];
  46260. this.rebuildInputCheck();
  46261. }
  46262. }
  46263. };
  46264. /**
  46265. * Remove a specific input type from a camera
  46266. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46267. * @param inputType the type of the input to remove
  46268. */
  46269. CameraInputsManager.prototype.removeByType = function (inputType) {
  46270. for (var cam in this.attached) {
  46271. var input = this.attached[cam];
  46272. if (input.getClassName() === inputType) {
  46273. input.detachControl(this.attachedElement);
  46274. input.camera = null;
  46275. delete this.attached[cam];
  46276. this.rebuildInputCheck();
  46277. }
  46278. }
  46279. };
  46280. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46281. var current = this.checkInputs;
  46282. return function () {
  46283. current();
  46284. fn();
  46285. };
  46286. };
  46287. /**
  46288. * Attach the input controls to the currently attached dom element to listen the events from.
  46289. * @param input Defines the input to attach
  46290. */
  46291. CameraInputsManager.prototype.attachInput = function (input) {
  46292. if (this.attachedElement) {
  46293. input.attachControl(this.attachedElement, this.noPreventDefault);
  46294. }
  46295. };
  46296. /**
  46297. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46298. * @param element Defines the dom element to collect the events from
  46299. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46300. */
  46301. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46302. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46303. if (this.attachedElement) {
  46304. return;
  46305. }
  46306. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46307. this.attachedElement = element;
  46308. this.noPreventDefault = noPreventDefault;
  46309. for (var cam in this.attached) {
  46310. this.attached[cam].attachControl(element, noPreventDefault);
  46311. }
  46312. };
  46313. /**
  46314. * Detach the current manager inputs controls from a specific dom element.
  46315. * @param element Defines the dom element to collect the events from
  46316. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46317. */
  46318. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46319. if (disconnect === void 0) { disconnect = false; }
  46320. if (this.attachedElement !== element) {
  46321. return;
  46322. }
  46323. for (var cam in this.attached) {
  46324. this.attached[cam].detachControl(element);
  46325. if (disconnect) {
  46326. this.attached[cam].camera = null;
  46327. }
  46328. }
  46329. this.attachedElement = null;
  46330. };
  46331. /**
  46332. * Rebuild the dynamic inputCheck function from the current list of
  46333. * defined inputs in the manager.
  46334. */
  46335. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46336. this.checkInputs = function () { };
  46337. for (var cam in this.attached) {
  46338. var input = this.attached[cam];
  46339. if (input.checkInputs) {
  46340. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46341. }
  46342. }
  46343. };
  46344. /**
  46345. * Remove all attached input methods from a camera
  46346. */
  46347. CameraInputsManager.prototype.clear = function () {
  46348. if (this.attachedElement) {
  46349. this.detachElement(this.attachedElement, true);
  46350. }
  46351. this.attached = {};
  46352. this.attachedElement = null;
  46353. this.checkInputs = function () { };
  46354. };
  46355. /**
  46356. * Serialize the current input manager attached to a camera.
  46357. * This ensures than once parsed,
  46358. * the input associated to the camera will be identical to the current ones
  46359. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46360. */
  46361. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46362. var inputs = {};
  46363. for (var cam in this.attached) {
  46364. var input = this.attached[cam];
  46365. var res = BABYLON.SerializationHelper.Serialize(input);
  46366. inputs[input.getClassName()] = res;
  46367. }
  46368. serializedCamera.inputsmgr = inputs;
  46369. };
  46370. /**
  46371. * Parses an input manager serialized JSON to restore the previous list of inputs
  46372. * and states associated to a camera.
  46373. * @param parsedCamera Defines the JSON to parse
  46374. */
  46375. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46376. var parsedInputs = parsedCamera.inputsmgr;
  46377. if (parsedInputs) {
  46378. this.clear();
  46379. for (var n in parsedInputs) {
  46380. var construct = BABYLON.CameraInputTypes[n];
  46381. if (construct) {
  46382. var parsedinput = parsedInputs[n];
  46383. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46384. this.add(input);
  46385. }
  46386. }
  46387. }
  46388. else {
  46389. //2016-03-08 this part is for managing backward compatibility
  46390. for (var n in this.attached) {
  46391. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46392. if (construct) {
  46393. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46394. this.remove(this.attached[n]);
  46395. this.add(input);
  46396. }
  46397. }
  46398. }
  46399. };
  46400. return CameraInputsManager;
  46401. }());
  46402. BABYLON.CameraInputsManager = CameraInputsManager;
  46403. })(BABYLON || (BABYLON = {}));
  46404. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46405. var BABYLON;
  46406. (function (BABYLON) {
  46407. /**
  46408. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46409. * This is the base of the follow, arc rotate cameras and Free camera
  46410. * @see http://doc.babylonjs.com/features/cameras
  46411. */
  46412. var TargetCamera = /** @class */ (function (_super) {
  46413. __extends(TargetCamera, _super);
  46414. /**
  46415. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46416. * This is the base of the follow, arc rotate cameras and Free camera
  46417. * @see http://doc.babylonjs.com/features/cameras
  46418. * @param name Defines the name of the camera in the scene
  46419. * @param position Defines the start position of the camera in the scene
  46420. * @param scene Defines the scene the camera belongs to
  46421. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46422. */
  46423. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46424. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46425. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46426. /**
  46427. * Define the current direction the camera is moving to
  46428. */
  46429. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46430. /**
  46431. * Define the current rotation the camera is rotating to
  46432. */
  46433. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46434. /**
  46435. * Define the current rotation of the camera
  46436. */
  46437. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46438. /**
  46439. * Define the current speed of the camera
  46440. */
  46441. _this.speed = 2.0;
  46442. /**
  46443. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46444. * around all axis.
  46445. */
  46446. _this.noRotationConstraint = false;
  46447. /**
  46448. * Define the current target of the camera as an object or a position.
  46449. */
  46450. _this.lockedTarget = null;
  46451. /** @hidden */
  46452. _this._currentTarget = BABYLON.Vector3.Zero();
  46453. /** @hidden */
  46454. _this._viewMatrix = BABYLON.Matrix.Zero();
  46455. /** @hidden */
  46456. _this._camMatrix = BABYLON.Matrix.Zero();
  46457. /** @hidden */
  46458. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46459. /** @hidden */
  46460. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46461. /** @hidden */
  46462. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46463. /** @hidden */
  46464. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46465. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46466. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46467. _this._defaultUp = BABYLON.Vector3.Up();
  46468. _this._cachedRotationZ = 0;
  46469. return _this;
  46470. }
  46471. /**
  46472. * Gets the position in front of the camera at a given distance.
  46473. * @param distance The distance from the camera we want the position to be
  46474. * @returns the position
  46475. */
  46476. TargetCamera.prototype.getFrontPosition = function (distance) {
  46477. this.getWorldMatrix();
  46478. var direction = this.getTarget().subtract(this.position);
  46479. direction.normalize();
  46480. direction.scaleInPlace(distance);
  46481. return this.globalPosition.add(direction);
  46482. };
  46483. /** @hidden */
  46484. TargetCamera.prototype._getLockedTargetPosition = function () {
  46485. if (!this.lockedTarget) {
  46486. return null;
  46487. }
  46488. if (this.lockedTarget.absolutePosition) {
  46489. this.lockedTarget.computeWorldMatrix();
  46490. }
  46491. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46492. };
  46493. /**
  46494. * Store current camera state of the camera (fov, position, rotation, etc..)
  46495. * @returns the camera
  46496. */
  46497. TargetCamera.prototype.storeState = function () {
  46498. this._storedPosition = this.position.clone();
  46499. this._storedRotation = this.rotation.clone();
  46500. if (this.rotationQuaternion) {
  46501. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46502. }
  46503. return _super.prototype.storeState.call(this);
  46504. };
  46505. /**
  46506. * Restored camera state. You must call storeState() first
  46507. * @returns whether it was successful or not
  46508. * @hidden
  46509. */
  46510. TargetCamera.prototype._restoreStateValues = function () {
  46511. if (!_super.prototype._restoreStateValues.call(this)) {
  46512. return false;
  46513. }
  46514. this.position = this._storedPosition.clone();
  46515. this.rotation = this._storedRotation.clone();
  46516. if (this.rotationQuaternion) {
  46517. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46518. }
  46519. this.cameraDirection.copyFromFloats(0, 0, 0);
  46520. this.cameraRotation.copyFromFloats(0, 0);
  46521. return true;
  46522. };
  46523. /** @hidden */
  46524. TargetCamera.prototype._initCache = function () {
  46525. _super.prototype._initCache.call(this);
  46526. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46527. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46528. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46529. };
  46530. /** @hidden */
  46531. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46532. if (!ignoreParentClass) {
  46533. _super.prototype._updateCache.call(this);
  46534. }
  46535. var lockedTargetPosition = this._getLockedTargetPosition();
  46536. if (!lockedTargetPosition) {
  46537. this._cache.lockedTarget = null;
  46538. }
  46539. else {
  46540. if (!this._cache.lockedTarget) {
  46541. this._cache.lockedTarget = lockedTargetPosition.clone();
  46542. }
  46543. else {
  46544. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46545. }
  46546. }
  46547. this._cache.rotation.copyFrom(this.rotation);
  46548. if (this.rotationQuaternion)
  46549. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46550. };
  46551. // Synchronized
  46552. /** @hidden */
  46553. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46554. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46555. return false;
  46556. }
  46557. var lockedTargetPosition = this._getLockedTargetPosition();
  46558. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46559. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46560. };
  46561. // Methods
  46562. /** @hidden */
  46563. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46564. var engine = this.getEngine();
  46565. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46566. };
  46567. // Target
  46568. /** @hidden */
  46569. TargetCamera.prototype.setTarget = function (target) {
  46570. this.upVector.normalize();
  46571. if (this.position.z === target.z) {
  46572. this.position.z += BABYLON.Epsilon;
  46573. }
  46574. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46575. this._camMatrix.invert();
  46576. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46577. var vDir = target.subtract(this.position);
  46578. if (vDir.x >= 0.0) {
  46579. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46580. }
  46581. else {
  46582. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46583. }
  46584. this.rotation.z = 0;
  46585. if (isNaN(this.rotation.x)) {
  46586. this.rotation.x = 0;
  46587. }
  46588. if (isNaN(this.rotation.y)) {
  46589. this.rotation.y = 0;
  46590. }
  46591. if (isNaN(this.rotation.z)) {
  46592. this.rotation.z = 0;
  46593. }
  46594. if (this.rotationQuaternion) {
  46595. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46596. }
  46597. };
  46598. /**
  46599. * Return the current target position of the camera. This value is expressed in local space.
  46600. * @returns the target position
  46601. */
  46602. TargetCamera.prototype.getTarget = function () {
  46603. return this._currentTarget;
  46604. };
  46605. /** @hidden */
  46606. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46607. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46608. };
  46609. /** @hidden */
  46610. TargetCamera.prototype._updatePosition = function () {
  46611. if (this.parent) {
  46612. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46613. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46614. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46615. return;
  46616. }
  46617. this.position.addInPlace(this.cameraDirection);
  46618. };
  46619. /** @hidden */
  46620. TargetCamera.prototype._checkInputs = function () {
  46621. var needToMove = this._decideIfNeedsToMove();
  46622. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46623. // Move
  46624. if (needToMove) {
  46625. this._updatePosition();
  46626. }
  46627. // Rotate
  46628. if (needToRotate) {
  46629. this.rotation.x += this.cameraRotation.x;
  46630. this.rotation.y += this.cameraRotation.y;
  46631. //rotate, if quaternion is set and rotation was used
  46632. if (this.rotationQuaternion) {
  46633. var len = this.rotation.lengthSquared();
  46634. if (len) {
  46635. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46636. }
  46637. }
  46638. if (!this.noRotationConstraint) {
  46639. var limit = (Math.PI / 2) * 0.95;
  46640. if (this.rotation.x > limit)
  46641. this.rotation.x = limit;
  46642. if (this.rotation.x < -limit)
  46643. this.rotation.x = -limit;
  46644. }
  46645. }
  46646. // Inertia
  46647. if (needToMove) {
  46648. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46649. this.cameraDirection.x = 0;
  46650. }
  46651. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46652. this.cameraDirection.y = 0;
  46653. }
  46654. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46655. this.cameraDirection.z = 0;
  46656. }
  46657. this.cameraDirection.scaleInPlace(this.inertia);
  46658. }
  46659. if (needToRotate) {
  46660. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46661. this.cameraRotation.x = 0;
  46662. }
  46663. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46664. this.cameraRotation.y = 0;
  46665. }
  46666. this.cameraRotation.scaleInPlace(this.inertia);
  46667. }
  46668. _super.prototype._checkInputs.call(this);
  46669. };
  46670. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46671. if (this.rotationQuaternion) {
  46672. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46673. }
  46674. else {
  46675. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46676. }
  46677. };
  46678. /**
  46679. * 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)
  46680. * @returns the current camera
  46681. */
  46682. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46683. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46684. return this;
  46685. };
  46686. /** @hidden */
  46687. TargetCamera.prototype._getViewMatrix = function () {
  46688. if (this.lockedTarget) {
  46689. this.setTarget(this._getLockedTargetPosition());
  46690. }
  46691. // Compute
  46692. this._updateCameraRotationMatrix();
  46693. // Apply the changed rotation to the upVector.
  46694. if (this._cachedRotationZ != this.rotation.z) {
  46695. this._rotateUpVectorWithCameraRotationMatrix();
  46696. this._cachedRotationZ = this.rotation.z;
  46697. }
  46698. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46699. // Computing target and final matrix
  46700. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46701. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46702. return this._viewMatrix;
  46703. };
  46704. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46705. if (this.parent) {
  46706. var parentWorldMatrix = this.parent.getWorldMatrix();
  46707. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46708. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46709. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46710. this._markSyncedWithParent();
  46711. }
  46712. else {
  46713. this._globalPosition.copyFrom(position);
  46714. this._globalCurrentTarget.copyFrom(target);
  46715. this._globalCurrentUpVector.copyFrom(up);
  46716. }
  46717. if (this.getScene().useRightHandedSystem) {
  46718. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46719. }
  46720. else {
  46721. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46722. }
  46723. };
  46724. /**
  46725. * @hidden
  46726. */
  46727. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46728. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46729. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46730. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46731. if (!this.rotationQuaternion) {
  46732. this.rotationQuaternion = new BABYLON.Quaternion();
  46733. }
  46734. rigCamera._cameraRigParams = {};
  46735. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46736. }
  46737. return rigCamera;
  46738. }
  46739. return null;
  46740. };
  46741. /**
  46742. * @hidden
  46743. */
  46744. TargetCamera.prototype._updateRigCameras = function () {
  46745. var camLeft = this._rigCameras[0];
  46746. var camRight = this._rigCameras[1];
  46747. switch (this.cameraRigMode) {
  46748. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46752. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46753. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46754. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46755. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46756. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46757. camLeft.setTarget(this.getTarget());
  46758. camRight.setTarget(this.getTarget());
  46759. break;
  46760. case BABYLON.Camera.RIG_MODE_VR:
  46761. if (camLeft.rotationQuaternion) {
  46762. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46763. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46764. }
  46765. else {
  46766. camLeft.rotation.copyFrom(this.rotation);
  46767. camRight.rotation.copyFrom(this.rotation);
  46768. }
  46769. camLeft.position.copyFrom(this.position);
  46770. camRight.position.copyFrom(this.position);
  46771. break;
  46772. }
  46773. _super.prototype._updateRigCameras.call(this);
  46774. };
  46775. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46776. if (!this._rigCamTransformMatrix) {
  46777. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46778. }
  46779. var target = this.getTarget();
  46780. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46781. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46782. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46783. };
  46784. /**
  46785. * Gets the current object class name.
  46786. * @return the class name
  46787. */
  46788. TargetCamera.prototype.getClassName = function () {
  46789. return "TargetCamera";
  46790. };
  46791. __decorate([
  46792. BABYLON.serializeAsVector3()
  46793. ], TargetCamera.prototype, "rotation", void 0);
  46794. __decorate([
  46795. BABYLON.serialize()
  46796. ], TargetCamera.prototype, "speed", void 0);
  46797. __decorate([
  46798. BABYLON.serializeAsMeshReference("lockedTargetId")
  46799. ], TargetCamera.prototype, "lockedTarget", void 0);
  46800. return TargetCamera;
  46801. }(BABYLON.Camera));
  46802. BABYLON.TargetCamera = TargetCamera;
  46803. })(BABYLON || (BABYLON = {}));
  46804. //# sourceMappingURL=babylon.targetCamera.js.map
  46805. var BABYLON;
  46806. (function (BABYLON) {
  46807. /**
  46808. * Manage the mouse inputs to control the movement of a free camera.
  46809. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46810. */
  46811. var FreeCameraMouseInput = /** @class */ (function () {
  46812. /**
  46813. * Manage the mouse inputs to control the movement of a free camera.
  46814. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46815. * @param touchEnabled Defines if touch is enabled or not
  46816. */
  46817. function FreeCameraMouseInput(
  46818. /**
  46819. * Define if touch is enabled in the mouse input
  46820. */
  46821. touchEnabled) {
  46822. if (touchEnabled === void 0) { touchEnabled = true; }
  46823. this.touchEnabled = touchEnabled;
  46824. /**
  46825. * Defines the buttons associated with the input to handle camera move.
  46826. */
  46827. this.buttons = [0, 1, 2];
  46828. /**
  46829. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46830. */
  46831. this.angularSensibility = 2000.0;
  46832. this.previousPosition = null;
  46833. }
  46834. /**
  46835. * Attach the input controls to a specific dom element to get the input from.
  46836. * @param element Defines the element the controls should be listened from
  46837. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46838. */
  46839. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46840. var _this = this;
  46841. var engine = this.camera.getEngine();
  46842. if (!this._pointerInput) {
  46843. this._pointerInput = function (p, s) {
  46844. var evt = p.event;
  46845. if (engine.isInVRExclusivePointerMode) {
  46846. return;
  46847. }
  46848. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46849. return;
  46850. }
  46851. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46852. return;
  46853. }
  46854. var srcElement = (evt.srcElement || evt.target);
  46855. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46856. try {
  46857. srcElement.setPointerCapture(evt.pointerId);
  46858. }
  46859. catch (e) {
  46860. //Nothing to do with the error. Execution will continue.
  46861. }
  46862. _this.previousPosition = {
  46863. x: evt.clientX,
  46864. y: evt.clientY
  46865. };
  46866. if (!noPreventDefault) {
  46867. evt.preventDefault();
  46868. element.focus();
  46869. }
  46870. }
  46871. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46872. try {
  46873. srcElement.releasePointerCapture(evt.pointerId);
  46874. }
  46875. catch (e) {
  46876. //Nothing to do with the error.
  46877. }
  46878. _this.previousPosition = null;
  46879. if (!noPreventDefault) {
  46880. evt.preventDefault();
  46881. }
  46882. }
  46883. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46884. if (!_this.previousPosition || engine.isPointerLock) {
  46885. return;
  46886. }
  46887. var offsetX = evt.clientX - _this.previousPosition.x;
  46888. if (_this.camera.getScene().useRightHandedSystem)
  46889. offsetX *= -1;
  46890. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46891. offsetX *= -1;
  46892. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46893. var offsetY = evt.clientY - _this.previousPosition.y;
  46894. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46895. _this.previousPosition = {
  46896. x: evt.clientX,
  46897. y: evt.clientY
  46898. };
  46899. if (!noPreventDefault) {
  46900. evt.preventDefault();
  46901. }
  46902. }
  46903. };
  46904. }
  46905. this._onMouseMove = function (evt) {
  46906. if (!engine.isPointerLock) {
  46907. return;
  46908. }
  46909. if (engine.isInVRExclusivePointerMode) {
  46910. return;
  46911. }
  46912. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46913. if (_this.camera.getScene().useRightHandedSystem)
  46914. offsetX *= -1;
  46915. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46916. offsetX *= -1;
  46917. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46918. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46919. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46920. _this.previousPosition = null;
  46921. if (!noPreventDefault) {
  46922. evt.preventDefault();
  46923. }
  46924. };
  46925. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46926. element.addEventListener("mousemove", this._onMouseMove, false);
  46927. };
  46928. /**
  46929. * Detach the current controls from the specified dom element.
  46930. * @param element Defines the element to stop listening the inputs from
  46931. */
  46932. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46933. if (this._observer && element) {
  46934. this.camera.getScene().onPointerObservable.remove(this._observer);
  46935. if (this._onMouseMove) {
  46936. element.removeEventListener("mousemove", this._onMouseMove);
  46937. }
  46938. this._observer = null;
  46939. this._onMouseMove = null;
  46940. this.previousPosition = null;
  46941. }
  46942. };
  46943. /**
  46944. * Gets the class name of the current intput.
  46945. * @returns the class name
  46946. */
  46947. FreeCameraMouseInput.prototype.getClassName = function () {
  46948. return "FreeCameraMouseInput";
  46949. };
  46950. /**
  46951. * Get the friendly name associated with the input class.
  46952. * @returns the input friendly name
  46953. */
  46954. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46955. return "mouse";
  46956. };
  46957. __decorate([
  46958. BABYLON.serialize()
  46959. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46960. __decorate([
  46961. BABYLON.serialize()
  46962. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46963. return FreeCameraMouseInput;
  46964. }());
  46965. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46966. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46967. })(BABYLON || (BABYLON = {}));
  46968. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46969. var BABYLON;
  46970. (function (BABYLON) {
  46971. /**
  46972. * Manage the keyboard inputs to control the movement of a free camera.
  46973. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46974. */
  46975. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46976. function FreeCameraKeyboardMoveInput() {
  46977. /**
  46978. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  46979. */
  46980. this.keysUp = [38];
  46981. /**
  46982. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  46983. */
  46984. this.keysDown = [40];
  46985. /**
  46986. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  46987. */
  46988. this.keysLeft = [37];
  46989. /**
  46990. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  46991. */
  46992. this.keysRight = [39];
  46993. this._keys = new Array();
  46994. }
  46995. /**
  46996. * Attach the input controls to a specific dom element to get the input from.
  46997. * @param element Defines the element the controls should be listened from
  46998. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46999. */
  47000. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47001. var _this = this;
  47002. if (this._onCanvasBlurObserver) {
  47003. return;
  47004. }
  47005. this._scene = this.camera.getScene();
  47006. this._engine = this._scene.getEngine();
  47007. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47008. _this._keys = [];
  47009. });
  47010. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47011. var evt = info.event;
  47012. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47013. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47014. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47015. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47016. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47017. var index = _this._keys.indexOf(evt.keyCode);
  47018. if (index === -1) {
  47019. _this._keys.push(evt.keyCode);
  47020. }
  47021. if (!noPreventDefault) {
  47022. evt.preventDefault();
  47023. }
  47024. }
  47025. }
  47026. else {
  47027. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47028. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47029. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47030. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47031. var index = _this._keys.indexOf(evt.keyCode);
  47032. if (index >= 0) {
  47033. _this._keys.splice(index, 1);
  47034. }
  47035. if (!noPreventDefault) {
  47036. evt.preventDefault();
  47037. }
  47038. }
  47039. }
  47040. });
  47041. };
  47042. /**
  47043. * Detach the current controls from the specified dom element.
  47044. * @param element Defines the element to stop listening the inputs from
  47045. */
  47046. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47047. if (this._scene) {
  47048. if (this._onKeyboardObserver) {
  47049. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47050. }
  47051. if (this._onCanvasBlurObserver) {
  47052. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47053. }
  47054. this._onKeyboardObserver = null;
  47055. this._onCanvasBlurObserver = null;
  47056. }
  47057. this._keys = [];
  47058. };
  47059. /**
  47060. * Update the current camera state depending on the inputs that have been used this frame.
  47061. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47062. */
  47063. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47064. if (this._onKeyboardObserver) {
  47065. var camera = this.camera;
  47066. // Keyboard
  47067. for (var index = 0; index < this._keys.length; index++) {
  47068. var keyCode = this._keys[index];
  47069. var speed = camera._computeLocalCameraSpeed();
  47070. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47071. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47072. }
  47073. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47074. camera._localDirection.copyFromFloats(0, 0, speed);
  47075. }
  47076. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47077. camera._localDirection.copyFromFloats(speed, 0, 0);
  47078. }
  47079. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47080. camera._localDirection.copyFromFloats(0, 0, -speed);
  47081. }
  47082. if (camera.getScene().useRightHandedSystem) {
  47083. camera._localDirection.z *= -1;
  47084. }
  47085. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47086. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47087. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47088. }
  47089. }
  47090. };
  47091. /**
  47092. * Gets the class name of the current intput.
  47093. * @returns the class name
  47094. */
  47095. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47096. return "FreeCameraKeyboardMoveInput";
  47097. };
  47098. /** @hidden */
  47099. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47100. this._keys = [];
  47101. };
  47102. /**
  47103. * Get the friendly name associated with the input class.
  47104. * @returns the input friendly name
  47105. */
  47106. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47107. return "keyboard";
  47108. };
  47109. __decorate([
  47110. BABYLON.serialize()
  47111. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47112. __decorate([
  47113. BABYLON.serialize()
  47114. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47115. __decorate([
  47116. BABYLON.serialize()
  47117. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47118. __decorate([
  47119. BABYLON.serialize()
  47120. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47121. return FreeCameraKeyboardMoveInput;
  47122. }());
  47123. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47124. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47125. })(BABYLON || (BABYLON = {}));
  47126. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47127. var BABYLON;
  47128. (function (BABYLON) {
  47129. /**
  47130. * Default Inputs manager for the FreeCamera.
  47131. * It groups all the default supported inputs for ease of use.
  47132. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47133. */
  47134. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47135. __extends(FreeCameraInputsManager, _super);
  47136. /**
  47137. * Instantiates a new FreeCameraInputsManager.
  47138. * @param camera Defines the camera the inputs belong to
  47139. */
  47140. function FreeCameraInputsManager(camera) {
  47141. return _super.call(this, camera) || this;
  47142. }
  47143. /**
  47144. * Add keyboard input support to the input manager.
  47145. * @returns the current input manager
  47146. */
  47147. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47148. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47149. return this;
  47150. };
  47151. /**
  47152. * Add mouse input support to the input manager.
  47153. * @returns the current input manager
  47154. */
  47155. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47156. if (touchEnabled === void 0) { touchEnabled = true; }
  47157. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47158. return this;
  47159. };
  47160. /**
  47161. * Add orientation input support to the input manager.
  47162. * @returns the current input manager
  47163. */
  47164. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47165. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47166. return this;
  47167. };
  47168. /**
  47169. * Add touch input support to the input manager.
  47170. * @returns the current input manager
  47171. */
  47172. FreeCameraInputsManager.prototype.addTouch = function () {
  47173. this.add(new BABYLON.FreeCameraTouchInput());
  47174. return this;
  47175. };
  47176. /**
  47177. * Add virtual joystick input support to the input manager.
  47178. * @returns the current input manager
  47179. */
  47180. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47181. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47182. return this;
  47183. };
  47184. return FreeCameraInputsManager;
  47185. }(BABYLON.CameraInputsManager));
  47186. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47187. })(BABYLON || (BABYLON = {}));
  47188. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47189. var BABYLON;
  47190. (function (BABYLON) {
  47191. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47192. // Forcing to use the Universal camera
  47193. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47194. });
  47195. /**
  47196. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47197. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47198. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47199. */
  47200. var FreeCamera = /** @class */ (function (_super) {
  47201. __extends(FreeCamera, _super);
  47202. /**
  47203. * Instantiates a Free Camera.
  47204. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47205. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47206. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47207. * @param name Define the name of the camera in the scene
  47208. * @param position Define the start position of the camera in the scene
  47209. * @param scene Define the scene the camera belongs to
  47210. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47211. */
  47212. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47213. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47214. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47215. /**
  47216. * Define the collision ellipsoid of the camera.
  47217. * This is helpful to simulate a camera body like the player body around the camera
  47218. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47219. */
  47220. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47221. /**
  47222. * Define an offset for the position of the ellipsoid around the camera.
  47223. * This can be helpful to determine the center of the body near the gravity center of the body
  47224. * instead of its head.
  47225. */
  47226. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47227. /**
  47228. * Enable or disable collisions of the camera with the rest of the scene objects.
  47229. */
  47230. _this.checkCollisions = false;
  47231. /**
  47232. * Enable or disable gravity on the camera.
  47233. */
  47234. _this.applyGravity = false;
  47235. _this._needMoveForGravity = false;
  47236. _this._oldPosition = BABYLON.Vector3.Zero();
  47237. _this._diffPosition = BABYLON.Vector3.Zero();
  47238. _this._newPosition = BABYLON.Vector3.Zero();
  47239. // Collisions
  47240. _this._collisionMask = -1;
  47241. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47242. if (collidedMesh === void 0) { collidedMesh = null; }
  47243. //TODO move this to the collision coordinator!
  47244. if (_this.getScene().workerCollisions)
  47245. newPosition.multiplyInPlace(_this._collider._radius);
  47246. var updatePosition = function (newPos) {
  47247. _this._newPosition.copyFrom(newPos);
  47248. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47249. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47250. _this.position.addInPlace(_this._diffPosition);
  47251. if (_this.onCollide && collidedMesh) {
  47252. _this.onCollide(collidedMesh);
  47253. }
  47254. }
  47255. };
  47256. updatePosition(newPosition);
  47257. };
  47258. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47259. _this.inputs.addKeyboard().addMouse();
  47260. return _this;
  47261. }
  47262. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47263. /**
  47264. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47265. * Higher values reduce sensitivity.
  47266. */
  47267. get: function () {
  47268. var mouse = this.inputs.attached["mouse"];
  47269. if (mouse)
  47270. return mouse.angularSensibility;
  47271. return 0;
  47272. },
  47273. /**
  47274. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47275. * Higher values reduce sensitivity.
  47276. */
  47277. set: function (value) {
  47278. var mouse = this.inputs.attached["mouse"];
  47279. if (mouse)
  47280. mouse.angularSensibility = value;
  47281. },
  47282. enumerable: true,
  47283. configurable: true
  47284. });
  47285. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47286. /**
  47287. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47288. */
  47289. get: function () {
  47290. var keyboard = this.inputs.attached["keyboard"];
  47291. if (keyboard)
  47292. return keyboard.keysUp;
  47293. return [];
  47294. },
  47295. set: function (value) {
  47296. var keyboard = this.inputs.attached["keyboard"];
  47297. if (keyboard)
  47298. keyboard.keysUp = value;
  47299. },
  47300. enumerable: true,
  47301. configurable: true
  47302. });
  47303. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47304. /**
  47305. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47306. */
  47307. get: function () {
  47308. var keyboard = this.inputs.attached["keyboard"];
  47309. if (keyboard)
  47310. return keyboard.keysDown;
  47311. return [];
  47312. },
  47313. set: function (value) {
  47314. var keyboard = this.inputs.attached["keyboard"];
  47315. if (keyboard)
  47316. keyboard.keysDown = value;
  47317. },
  47318. enumerable: true,
  47319. configurable: true
  47320. });
  47321. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47322. /**
  47323. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47324. */
  47325. get: function () {
  47326. var keyboard = this.inputs.attached["keyboard"];
  47327. if (keyboard)
  47328. return keyboard.keysLeft;
  47329. return [];
  47330. },
  47331. set: function (value) {
  47332. var keyboard = this.inputs.attached["keyboard"];
  47333. if (keyboard)
  47334. keyboard.keysLeft = value;
  47335. },
  47336. enumerable: true,
  47337. configurable: true
  47338. });
  47339. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47340. /**
  47341. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47342. */
  47343. get: function () {
  47344. var keyboard = this.inputs.attached["keyboard"];
  47345. if (keyboard)
  47346. return keyboard.keysRight;
  47347. return [];
  47348. },
  47349. set: function (value) {
  47350. var keyboard = this.inputs.attached["keyboard"];
  47351. if (keyboard)
  47352. keyboard.keysRight = value;
  47353. },
  47354. enumerable: true,
  47355. configurable: true
  47356. });
  47357. /**
  47358. * Attached controls to the current camera.
  47359. * @param element Defines the element the controls should be listened from
  47360. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47361. */
  47362. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47363. this.inputs.attachElement(element, noPreventDefault);
  47364. };
  47365. /**
  47366. * Detach the current controls from the camera.
  47367. * The camera will stop reacting to inputs.
  47368. * @param element Defines the element to stop listening the inputs from
  47369. */
  47370. FreeCamera.prototype.detachControl = function (element) {
  47371. this.inputs.detachElement(element);
  47372. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47373. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47374. };
  47375. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47376. /**
  47377. * Define a collision mask to limit the list of object the camera can collide with
  47378. */
  47379. get: function () {
  47380. return this._collisionMask;
  47381. },
  47382. set: function (mask) {
  47383. this._collisionMask = !isNaN(mask) ? mask : -1;
  47384. },
  47385. enumerable: true,
  47386. configurable: true
  47387. });
  47388. /** @hidden */
  47389. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47390. var globalPosition;
  47391. if (this.parent) {
  47392. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47393. }
  47394. else {
  47395. globalPosition = this.position;
  47396. }
  47397. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47398. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47399. if (!this._collider) {
  47400. this._collider = new BABYLON.Collider();
  47401. }
  47402. this._collider._radius = this.ellipsoid;
  47403. this._collider.collisionMask = this._collisionMask;
  47404. //no need for clone, as long as gravity is not on.
  47405. var actualDisplacement = displacement;
  47406. //add gravity to the direction to prevent the dual-collision checking
  47407. if (this.applyGravity) {
  47408. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47409. actualDisplacement = displacement.add(this.getScene().gravity);
  47410. }
  47411. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47412. };
  47413. /** @hidden */
  47414. FreeCamera.prototype._checkInputs = function () {
  47415. if (!this._localDirection) {
  47416. this._localDirection = BABYLON.Vector3.Zero();
  47417. this._transformedDirection = BABYLON.Vector3.Zero();
  47418. }
  47419. this.inputs.checkInputs();
  47420. _super.prototype._checkInputs.call(this);
  47421. };
  47422. /** @hidden */
  47423. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47424. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47425. };
  47426. /** @hidden */
  47427. FreeCamera.prototype._updatePosition = function () {
  47428. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47429. this._collideWithWorld(this.cameraDirection);
  47430. }
  47431. else {
  47432. _super.prototype._updatePosition.call(this);
  47433. }
  47434. };
  47435. /**
  47436. * Destroy the camera and release the current resources hold by it.
  47437. */
  47438. FreeCamera.prototype.dispose = function () {
  47439. this.inputs.clear();
  47440. _super.prototype.dispose.call(this);
  47441. };
  47442. /**
  47443. * Gets the current object class name.
  47444. * @return the class name
  47445. */
  47446. FreeCamera.prototype.getClassName = function () {
  47447. return "FreeCamera";
  47448. };
  47449. __decorate([
  47450. BABYLON.serializeAsVector3()
  47451. ], FreeCamera.prototype, "ellipsoid", void 0);
  47452. __decorate([
  47453. BABYLON.serializeAsVector3()
  47454. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47455. __decorate([
  47456. BABYLON.serialize()
  47457. ], FreeCamera.prototype, "checkCollisions", void 0);
  47458. __decorate([
  47459. BABYLON.serialize()
  47460. ], FreeCamera.prototype, "applyGravity", void 0);
  47461. return FreeCamera;
  47462. }(BABYLON.TargetCamera));
  47463. BABYLON.FreeCamera = FreeCamera;
  47464. })(BABYLON || (BABYLON = {}));
  47465. //# sourceMappingURL=babylon.freeCamera.js.map
  47466. var BABYLON;
  47467. (function (BABYLON) {
  47468. /**
  47469. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47470. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47471. */
  47472. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47473. function ArcRotateCameraKeyboardMoveInput() {
  47474. /**
  47475. * Defines the list of key codes associated with the up action (increase alpha)
  47476. */
  47477. this.keysUp = [38];
  47478. /**
  47479. * Defines the list of key codes associated with the down action (decrease alpha)
  47480. */
  47481. this.keysDown = [40];
  47482. /**
  47483. * Defines the list of key codes associated with the left action (increase beta)
  47484. */
  47485. this.keysLeft = [37];
  47486. /**
  47487. * Defines the list of key codes associated with the right action (decrease beta)
  47488. */
  47489. this.keysRight = [39];
  47490. /**
  47491. * Defines the list of key codes associated with the reset action.
  47492. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47493. */
  47494. this.keysReset = [220];
  47495. /**
  47496. * Defines the panning sensibility of the inputs.
  47497. * (How fast is the camera paning)
  47498. */
  47499. this.panningSensibility = 50.0;
  47500. /**
  47501. * Defines the zooming sensibility of the inputs.
  47502. * (How fast is the camera zooming)
  47503. */
  47504. this.zoomingSensibility = 25.0;
  47505. /**
  47506. * Defines wether maintaining the alt key down switch the movement mode from
  47507. * orientation to zoom.
  47508. */
  47509. this.useAltToZoom = true;
  47510. this._keys = new Array();
  47511. }
  47512. /**
  47513. * Attach the input controls to a specific dom element to get the input from.
  47514. * @param element Defines the element the controls should be listened from
  47515. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47516. */
  47517. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47518. var _this = this;
  47519. if (this._onCanvasBlurObserver) {
  47520. return;
  47521. }
  47522. this._scene = this.camera.getScene();
  47523. this._engine = this._scene.getEngine();
  47524. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47525. _this._keys = [];
  47526. });
  47527. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47528. var evt = info.event;
  47529. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47530. _this._ctrlPressed = evt.ctrlKey;
  47531. _this._altPressed = evt.altKey;
  47532. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47533. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47534. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47535. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47536. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47537. var index = _this._keys.indexOf(evt.keyCode);
  47538. if (index === -1) {
  47539. _this._keys.push(evt.keyCode);
  47540. }
  47541. if (evt.preventDefault) {
  47542. if (!noPreventDefault) {
  47543. evt.preventDefault();
  47544. }
  47545. }
  47546. }
  47547. }
  47548. else {
  47549. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47550. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47551. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47552. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47553. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47554. var index = _this._keys.indexOf(evt.keyCode);
  47555. if (index >= 0) {
  47556. _this._keys.splice(index, 1);
  47557. }
  47558. if (evt.preventDefault) {
  47559. if (!noPreventDefault) {
  47560. evt.preventDefault();
  47561. }
  47562. }
  47563. }
  47564. }
  47565. });
  47566. };
  47567. /**
  47568. * Detach the current controls from the specified dom element.
  47569. * @param element Defines the element to stop listening the inputs from
  47570. */
  47571. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47572. if (this._scene) {
  47573. if (this._onKeyboardObserver) {
  47574. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47575. }
  47576. if (this._onCanvasBlurObserver) {
  47577. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47578. }
  47579. this._onKeyboardObserver = null;
  47580. this._onCanvasBlurObserver = null;
  47581. }
  47582. this._keys = [];
  47583. };
  47584. /**
  47585. * Update the current camera state depending on the inputs that have been used this frame.
  47586. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47587. */
  47588. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47589. if (this._onKeyboardObserver) {
  47590. var camera = this.camera;
  47591. for (var index = 0; index < this._keys.length; index++) {
  47592. var keyCode = this._keys[index];
  47593. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47594. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47595. camera.inertialPanningX -= 1 / this.panningSensibility;
  47596. }
  47597. else {
  47598. camera.inertialAlphaOffset -= 0.01;
  47599. }
  47600. }
  47601. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47602. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47603. camera.inertialPanningY += 1 / this.panningSensibility;
  47604. }
  47605. else if (this._altPressed && this.useAltToZoom) {
  47606. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47607. }
  47608. else {
  47609. camera.inertialBetaOffset -= 0.01;
  47610. }
  47611. }
  47612. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47613. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47614. camera.inertialPanningX += 1 / this.panningSensibility;
  47615. }
  47616. else {
  47617. camera.inertialAlphaOffset += 0.01;
  47618. }
  47619. }
  47620. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47621. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47622. camera.inertialPanningY -= 1 / this.panningSensibility;
  47623. }
  47624. else if (this._altPressed && this.useAltToZoom) {
  47625. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47626. }
  47627. else {
  47628. camera.inertialBetaOffset += 0.01;
  47629. }
  47630. }
  47631. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47632. if (camera.useInputToRestoreState) {
  47633. camera.restoreState();
  47634. }
  47635. }
  47636. }
  47637. }
  47638. };
  47639. /**
  47640. * Gets the class name of the current intput.
  47641. * @returns the class name
  47642. */
  47643. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47644. return "ArcRotateCameraKeyboardMoveInput";
  47645. };
  47646. /**
  47647. * Get the friendly name associated with the input class.
  47648. * @returns the input friendly name
  47649. */
  47650. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47651. return "keyboard";
  47652. };
  47653. __decorate([
  47654. BABYLON.serialize()
  47655. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47656. __decorate([
  47657. BABYLON.serialize()
  47658. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47659. __decorate([
  47660. BABYLON.serialize()
  47661. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47662. __decorate([
  47663. BABYLON.serialize()
  47664. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47665. __decorate([
  47666. BABYLON.serialize()
  47667. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47668. __decorate([
  47669. BABYLON.serialize()
  47670. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47671. __decorate([
  47672. BABYLON.serialize()
  47673. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47674. __decorate([
  47675. BABYLON.serialize()
  47676. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47677. return ArcRotateCameraKeyboardMoveInput;
  47678. }());
  47679. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47680. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47681. })(BABYLON || (BABYLON = {}));
  47682. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47683. var BABYLON;
  47684. (function (BABYLON) {
  47685. /**
  47686. * Manage the mouse wheel inputs to control an arc rotate camera.
  47687. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47688. */
  47689. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47690. function ArcRotateCameraMouseWheelInput() {
  47691. /**
  47692. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47693. */
  47694. this.wheelPrecision = 3.0;
  47695. /**
  47696. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47697. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47698. */
  47699. this.wheelDeltaPercentage = 0;
  47700. }
  47701. /**
  47702. * Attach the input controls to a specific dom element to get the input from.
  47703. * @param element Defines the element the controls should be listened from
  47704. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47705. */
  47706. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47707. var _this = this;
  47708. this._wheel = function (p, s) {
  47709. //sanity check - this should be a PointerWheel event.
  47710. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47711. return;
  47712. var event = p.event;
  47713. var delta = 0;
  47714. if (event.wheelDelta) {
  47715. if (_this.wheelDeltaPercentage) {
  47716. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47717. if (event.wheelDelta > 0) {
  47718. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47719. }
  47720. else {
  47721. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47722. }
  47723. }
  47724. else {
  47725. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47726. }
  47727. }
  47728. else if (event.detail) {
  47729. delta = -event.detail / _this.wheelPrecision;
  47730. }
  47731. if (delta)
  47732. _this.camera.inertialRadiusOffset += delta;
  47733. if (event.preventDefault) {
  47734. if (!noPreventDefault) {
  47735. event.preventDefault();
  47736. }
  47737. }
  47738. };
  47739. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47740. };
  47741. /**
  47742. * Detach the current controls from the specified dom element.
  47743. * @param element Defines the element to stop listening the inputs from
  47744. */
  47745. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47746. if (this._observer && element) {
  47747. this.camera.getScene().onPointerObservable.remove(this._observer);
  47748. this._observer = null;
  47749. this._wheel = null;
  47750. }
  47751. };
  47752. /**
  47753. * Gets the class name of the current intput.
  47754. * @returns the class name
  47755. */
  47756. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47757. return "ArcRotateCameraMouseWheelInput";
  47758. };
  47759. /**
  47760. * Get the friendly name associated with the input class.
  47761. * @returns the input friendly name
  47762. */
  47763. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47764. return "mousewheel";
  47765. };
  47766. __decorate([
  47767. BABYLON.serialize()
  47768. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47769. __decorate([
  47770. BABYLON.serialize()
  47771. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47772. return ArcRotateCameraMouseWheelInput;
  47773. }());
  47774. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47775. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47776. })(BABYLON || (BABYLON = {}));
  47777. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47778. var BABYLON;
  47779. (function (BABYLON) {
  47780. /**
  47781. * Manage the pointers inputs to control an arc rotate camera.
  47782. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47783. */
  47784. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47785. function ArcRotateCameraPointersInput() {
  47786. /**
  47787. * Defines the buttons associated with the input to handle camera move.
  47788. */
  47789. this.buttons = [0, 1, 2];
  47790. /**
  47791. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47792. */
  47793. this.angularSensibilityX = 1000.0;
  47794. /**
  47795. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47796. */
  47797. this.angularSensibilityY = 1000.0;
  47798. /**
  47799. * Defines the pointer pinch precision or how fast is the camera zooming.
  47800. */
  47801. this.pinchPrecision = 12.0;
  47802. /**
  47803. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47804. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47805. */
  47806. this.pinchDeltaPercentage = 0;
  47807. /**
  47808. * Defines the pointer panning sensibility or how fast is the camera moving.
  47809. */
  47810. this.panningSensibility = 1000.0;
  47811. /**
  47812. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47813. */
  47814. this.multiTouchPanning = true;
  47815. /**
  47816. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47817. */
  47818. this.multiTouchPanAndZoom = true;
  47819. /**
  47820. * Revers pinch action direction.
  47821. */
  47822. this.pinchInwards = true;
  47823. this._isPanClick = false;
  47824. }
  47825. /**
  47826. * Attach the input controls to a specific dom element to get the input from.
  47827. * @param element Defines the element the controls should be listened from
  47828. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47829. */
  47830. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47831. var _this = this;
  47832. var engine = this.camera.getEngine();
  47833. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47834. var pointA = null;
  47835. var pointB = null;
  47836. var previousPinchSquaredDistance = 0;
  47837. var initialDistance = 0;
  47838. var twoFingerActivityCount = 0;
  47839. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47840. this._pointerInput = function (p, s) {
  47841. var evt = p.event;
  47842. var isTouch = p.event.pointerType === "touch";
  47843. if (engine.isInVRExclusivePointerMode) {
  47844. return;
  47845. }
  47846. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47847. return;
  47848. }
  47849. var srcElement = (evt.srcElement || evt.target);
  47850. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47851. try {
  47852. srcElement.setPointerCapture(evt.pointerId);
  47853. }
  47854. catch (e) {
  47855. //Nothing to do with the error. Execution will continue.
  47856. }
  47857. // Manage panning with pan button click
  47858. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47859. // manage pointers
  47860. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47861. if (pointA === null) {
  47862. pointA = cacheSoloPointer;
  47863. }
  47864. else if (pointB === null) {
  47865. pointB = cacheSoloPointer;
  47866. }
  47867. if (!noPreventDefault) {
  47868. evt.preventDefault();
  47869. element.focus();
  47870. }
  47871. }
  47872. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47873. if (_this.camera.useInputToRestoreState) {
  47874. _this.camera.restoreState();
  47875. }
  47876. }
  47877. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47878. try {
  47879. srcElement.releasePointerCapture(evt.pointerId);
  47880. }
  47881. catch (e) {
  47882. //Nothing to do with the error.
  47883. }
  47884. cacheSoloPointer = null;
  47885. previousPinchSquaredDistance = 0;
  47886. previousMultiTouchPanPosition.isPaning = false;
  47887. previousMultiTouchPanPosition.isPinching = false;
  47888. twoFingerActivityCount = 0;
  47889. initialDistance = 0;
  47890. if (!isTouch) {
  47891. pointB = null; // Mouse and pen are mono pointer
  47892. }
  47893. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47894. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47895. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47896. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47897. if (engine._badOS) {
  47898. pointA = pointB = null;
  47899. }
  47900. else {
  47901. //only remove the impacted pointer in case of multitouch allowing on most
  47902. //platforms switching from rotate to zoom and pan seamlessly.
  47903. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47904. pointA = pointB;
  47905. pointB = null;
  47906. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47907. }
  47908. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47909. pointB = null;
  47910. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47911. }
  47912. else {
  47913. pointA = pointB = null;
  47914. }
  47915. }
  47916. if (!noPreventDefault) {
  47917. evt.preventDefault();
  47918. }
  47919. }
  47920. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47921. if (!noPreventDefault) {
  47922. evt.preventDefault();
  47923. }
  47924. // One button down
  47925. if (pointA && pointB === null && cacheSoloPointer) {
  47926. if (_this.panningSensibility !== 0 &&
  47927. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47928. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47929. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47930. }
  47931. else {
  47932. var offsetX = evt.clientX - cacheSoloPointer.x;
  47933. var offsetY = evt.clientY - cacheSoloPointer.y;
  47934. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47935. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47936. }
  47937. cacheSoloPointer.x = evt.clientX;
  47938. cacheSoloPointer.y = evt.clientY;
  47939. }
  47940. // Two buttons down: pinch/pan
  47941. else if (pointA && pointB) {
  47942. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47943. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47944. ed.x = evt.clientX;
  47945. ed.y = evt.clientY;
  47946. var direction = _this.pinchInwards ? 1 : -1;
  47947. var distX = pointA.x - pointB.x;
  47948. var distY = pointA.y - pointB.y;
  47949. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47950. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47951. if (previousPinchSquaredDistance === 0) {
  47952. initialDistance = pinchDistance;
  47953. previousPinchSquaredDistance = pinchSquaredDistance;
  47954. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47955. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47956. return;
  47957. }
  47958. if (_this.multiTouchPanAndZoom) {
  47959. if (_this.pinchDeltaPercentage) {
  47960. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47961. }
  47962. else {
  47963. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47964. (_this.pinchPrecision *
  47965. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47966. direction);
  47967. }
  47968. if (_this.panningSensibility !== 0) {
  47969. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47970. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47971. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47972. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47973. previousMultiTouchPanPosition.x = pointersCenterX;
  47974. previousMultiTouchPanPosition.y = pointersCenterY;
  47975. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47976. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47977. }
  47978. }
  47979. else {
  47980. twoFingerActivityCount++;
  47981. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47982. if (_this.pinchDeltaPercentage) {
  47983. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47984. }
  47985. else {
  47986. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47987. (_this.pinchPrecision *
  47988. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47989. direction);
  47990. }
  47991. previousMultiTouchPanPosition.isPaning = false;
  47992. previousMultiTouchPanPosition.isPinching = true;
  47993. }
  47994. else {
  47995. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47996. if (!previousMultiTouchPanPosition.isPaning) {
  47997. previousMultiTouchPanPosition.isPaning = true;
  47998. previousMultiTouchPanPosition.isPinching = false;
  47999. previousMultiTouchPanPosition.x = ed.x;
  48000. previousMultiTouchPanPosition.y = ed.y;
  48001. return;
  48002. }
  48003. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48004. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48005. }
  48006. }
  48007. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48008. previousMultiTouchPanPosition.x = ed.x;
  48009. previousMultiTouchPanPosition.y = ed.y;
  48010. }
  48011. }
  48012. previousPinchSquaredDistance = pinchSquaredDistance;
  48013. }
  48014. }
  48015. };
  48016. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48017. this._onContextMenu = function (evt) {
  48018. evt.preventDefault();
  48019. };
  48020. if (!this.camera._useCtrlForPanning) {
  48021. element.addEventListener("contextmenu", this._onContextMenu, false);
  48022. }
  48023. this._onLostFocus = function () {
  48024. //this._keys = [];
  48025. pointA = pointB = null;
  48026. previousPinchSquaredDistance = 0;
  48027. previousMultiTouchPanPosition.isPaning = false;
  48028. previousMultiTouchPanPosition.isPinching = false;
  48029. twoFingerActivityCount = 0;
  48030. cacheSoloPointer = null;
  48031. initialDistance = 0;
  48032. };
  48033. this._onMouseMove = function (evt) {
  48034. if (!engine.isPointerLock) {
  48035. return;
  48036. }
  48037. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48038. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48039. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48040. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48041. if (!noPreventDefault) {
  48042. evt.preventDefault();
  48043. }
  48044. };
  48045. this._onGestureStart = function (e) {
  48046. if (window.MSGesture === undefined) {
  48047. return;
  48048. }
  48049. if (!_this._MSGestureHandler) {
  48050. _this._MSGestureHandler = new MSGesture();
  48051. _this._MSGestureHandler.target = element;
  48052. }
  48053. _this._MSGestureHandler.addPointer(e.pointerId);
  48054. };
  48055. this._onGesture = function (e) {
  48056. _this.camera.radius *= e.scale;
  48057. if (e.preventDefault) {
  48058. if (!noPreventDefault) {
  48059. e.stopPropagation();
  48060. e.preventDefault();
  48061. }
  48062. }
  48063. };
  48064. element.addEventListener("mousemove", this._onMouseMove, false);
  48065. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48066. element.addEventListener("MSGestureChange", this._onGesture, false);
  48067. BABYLON.Tools.RegisterTopRootEvents([
  48068. { name: "blur", handler: this._onLostFocus }
  48069. ]);
  48070. };
  48071. /**
  48072. * Detach the current controls from the specified dom element.
  48073. * @param element Defines the element to stop listening the inputs from
  48074. */
  48075. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48076. if (this._onLostFocus) {
  48077. BABYLON.Tools.UnregisterTopRootEvents([
  48078. { name: "blur", handler: this._onLostFocus }
  48079. ]);
  48080. }
  48081. if (element && this._observer) {
  48082. this.camera.getScene().onPointerObservable.remove(this._observer);
  48083. this._observer = null;
  48084. if (this._onContextMenu) {
  48085. element.removeEventListener("contextmenu", this._onContextMenu);
  48086. }
  48087. if (this._onMouseMove) {
  48088. element.removeEventListener("mousemove", this._onMouseMove);
  48089. }
  48090. if (this._onGestureStart) {
  48091. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48092. }
  48093. if (this._onGesture) {
  48094. element.removeEventListener("MSGestureChange", this._onGesture);
  48095. }
  48096. this._isPanClick = false;
  48097. this.pinchInwards = true;
  48098. this._onMouseMove = null;
  48099. this._onGestureStart = null;
  48100. this._onGesture = null;
  48101. this._MSGestureHandler = null;
  48102. this._onLostFocus = null;
  48103. this._onContextMenu = null;
  48104. }
  48105. };
  48106. /**
  48107. * Gets the class name of the current intput.
  48108. * @returns the class name
  48109. */
  48110. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48111. return "ArcRotateCameraPointersInput";
  48112. };
  48113. /**
  48114. * Get the friendly name associated with the input class.
  48115. * @returns the input friendly name
  48116. */
  48117. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48118. return "pointers";
  48119. };
  48120. __decorate([
  48121. BABYLON.serialize()
  48122. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48123. __decorate([
  48124. BABYLON.serialize()
  48125. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48126. __decorate([
  48127. BABYLON.serialize()
  48128. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48129. __decorate([
  48130. BABYLON.serialize()
  48131. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48132. __decorate([
  48133. BABYLON.serialize()
  48134. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48135. __decorate([
  48136. BABYLON.serialize()
  48137. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48138. __decorate([
  48139. BABYLON.serialize()
  48140. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48141. __decorate([
  48142. BABYLON.serialize()
  48143. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48144. return ArcRotateCameraPointersInput;
  48145. }());
  48146. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48147. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48148. })(BABYLON || (BABYLON = {}));
  48149. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48150. var BABYLON;
  48151. (function (BABYLON) {
  48152. /**
  48153. * Default Inputs manager for the ArcRotateCamera.
  48154. * It groups all the default supported inputs for ease of use.
  48155. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48156. */
  48157. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48158. __extends(ArcRotateCameraInputsManager, _super);
  48159. /**
  48160. * Instantiates a new ArcRotateCameraInputsManager.
  48161. * @param camera Defines the camera the inputs belong to
  48162. */
  48163. function ArcRotateCameraInputsManager(camera) {
  48164. return _super.call(this, camera) || this;
  48165. }
  48166. /**
  48167. * Add mouse wheel input support to the input manager.
  48168. * @returns the current input manager
  48169. */
  48170. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48171. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48172. return this;
  48173. };
  48174. /**
  48175. * Add pointers input support to the input manager.
  48176. * @returns the current input manager
  48177. */
  48178. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48179. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48180. return this;
  48181. };
  48182. /**
  48183. * Add keyboard input support to the input manager.
  48184. * @returns the current input manager
  48185. */
  48186. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48187. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48188. return this;
  48189. };
  48190. /**
  48191. * Add orientation input support to the input manager.
  48192. * @returns the current input manager
  48193. */
  48194. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48195. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48196. return this;
  48197. };
  48198. return ArcRotateCameraInputsManager;
  48199. }(BABYLON.CameraInputsManager));
  48200. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48201. })(BABYLON || (BABYLON = {}));
  48202. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48203. var BABYLON;
  48204. (function (BABYLON) {
  48205. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48206. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48207. });
  48208. /**
  48209. * This represents an orbital type of camera.
  48210. *
  48211. * 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.
  48212. * 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.
  48213. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48214. */
  48215. var ArcRotateCamera = /** @class */ (function (_super) {
  48216. __extends(ArcRotateCamera, _super);
  48217. /**
  48218. * Instantiates a new ArcRotateCamera in a given scene
  48219. * @param name Defines the name of the camera
  48220. * @param alpha Defines the camera rotation along the logitudinal axis
  48221. * @param beta Defines the camera rotation along the latitudinal axis
  48222. * @param radius Defines the camera distance from its target
  48223. * @param target Defines the camera target
  48224. * @param scene Defines the scene the camera belongs to
  48225. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48226. */
  48227. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48228. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48229. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48230. /**
  48231. * Current inertia value on the longitudinal axis.
  48232. * The bigger this number the longer it will take for the camera to stop.
  48233. */
  48234. _this.inertialAlphaOffset = 0;
  48235. /**
  48236. * Current inertia value on the latitudinal axis.
  48237. * The bigger this number the longer it will take for the camera to stop.
  48238. */
  48239. _this.inertialBetaOffset = 0;
  48240. /**
  48241. * Current inertia value on the radius axis.
  48242. * The bigger this number the longer it will take for the camera to stop.
  48243. */
  48244. _this.inertialRadiusOffset = 0;
  48245. /**
  48246. * Minimum allowed angle on the longitudinal axis.
  48247. * This can help limiting how the Camera is able to move in the scene.
  48248. */
  48249. _this.lowerAlphaLimit = null;
  48250. /**
  48251. * Maximum allowed angle on the longitudinal axis.
  48252. * This can help limiting how the Camera is able to move in the scene.
  48253. */
  48254. _this.upperAlphaLimit = null;
  48255. /**
  48256. * Minimum allowed angle on the latitudinal axis.
  48257. * This can help limiting how the Camera is able to move in the scene.
  48258. */
  48259. _this.lowerBetaLimit = 0.01;
  48260. /**
  48261. * Maximum allowed angle on the latitudinal axis.
  48262. * This can help limiting how the Camera is able to move in the scene.
  48263. */
  48264. _this.upperBetaLimit = Math.PI;
  48265. /**
  48266. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48267. * This can help limiting how the Camera is able to move in the scene.
  48268. */
  48269. _this.lowerRadiusLimit = null;
  48270. /**
  48271. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48272. * This can help limiting how the Camera is able to move in the scene.
  48273. */
  48274. _this.upperRadiusLimit = null;
  48275. /**
  48276. * Defines the current inertia value used during panning of the camera along the X axis.
  48277. */
  48278. _this.inertialPanningX = 0;
  48279. /**
  48280. * Defines the current inertia value used during panning of the camera along the Y axis.
  48281. */
  48282. _this.inertialPanningY = 0;
  48283. /**
  48284. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48285. * Basically if your fingers moves away from more than this distance you will be considered
  48286. * in pinch mode.
  48287. */
  48288. _this.pinchToPanMaxDistance = 20;
  48289. /**
  48290. * Defines the maximum distance the camera can pan.
  48291. * This could help keeping the cammera always in your scene.
  48292. */
  48293. _this.panningDistanceLimit = null;
  48294. /**
  48295. * Defines the target of the camera before paning.
  48296. */
  48297. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48298. /**
  48299. * Defines the value of the inertia used during panning.
  48300. * 0 would mean stop inertia and one would mean no decelleration at all.
  48301. */
  48302. _this.panningInertia = 0.9;
  48303. //-- end properties for backward compatibility for inputs
  48304. /**
  48305. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48306. */
  48307. _this.zoomOnFactor = 1;
  48308. /**
  48309. * Defines a screen offset for the camera position.
  48310. */
  48311. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48312. /**
  48313. * Allows the camera to be completely reversed.
  48314. * If false the camera can not arrive upside down.
  48315. */
  48316. _this.allowUpsideDown = true;
  48317. /**
  48318. * Define if double tap/click is used to restore the previously saved state of the camera.
  48319. */
  48320. _this.useInputToRestoreState = true;
  48321. /** @hidden */
  48322. _this._viewMatrix = new BABYLON.Matrix();
  48323. /**
  48324. * Defines the allowed panning axis.
  48325. */
  48326. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48327. /**
  48328. * Observable triggered when the mesh target has been changed on the camera.
  48329. */
  48330. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48331. /**
  48332. * Defines whether the camera should check collision with the objects oh the scene.
  48333. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48334. */
  48335. _this.checkCollisions = false;
  48336. /**
  48337. * Defines the collision radius of the camera.
  48338. * This simulates a sphere around the camera.
  48339. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48340. */
  48341. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48342. _this._previousPosition = BABYLON.Vector3.Zero();
  48343. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48344. _this._newPosition = BABYLON.Vector3.Zero();
  48345. _this._computationVector = BABYLON.Vector3.Zero();
  48346. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48347. if (collidedMesh === void 0) { collidedMesh = null; }
  48348. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48349. newPosition.multiplyInPlace(_this._collider._radius);
  48350. }
  48351. if (!collidedMesh) {
  48352. _this._previousPosition.copyFrom(_this.position);
  48353. }
  48354. else {
  48355. _this.setPosition(newPosition);
  48356. if (_this.onCollide) {
  48357. _this.onCollide(collidedMesh);
  48358. }
  48359. }
  48360. // Recompute because of constraints
  48361. var cosa = Math.cos(_this.alpha);
  48362. var sina = Math.sin(_this.alpha);
  48363. var cosb = Math.cos(_this.beta);
  48364. var sinb = Math.sin(_this.beta);
  48365. if (sinb === 0) {
  48366. sinb = 0.0001;
  48367. }
  48368. var target = _this._getTargetPosition();
  48369. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48370. target.addToRef(_this._computationVector, _this._newPosition);
  48371. _this.position.copyFrom(_this._newPosition);
  48372. var up = _this.upVector;
  48373. if (_this.allowUpsideDown && _this.beta < 0) {
  48374. up = up.clone();
  48375. up = up.negate();
  48376. }
  48377. _this._computeViewMatrix(_this.position, target, up);
  48378. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48379. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48380. _this._collisionTriggered = false;
  48381. };
  48382. _this._target = BABYLON.Vector3.Zero();
  48383. if (target) {
  48384. _this.setTarget(target);
  48385. }
  48386. _this.alpha = alpha;
  48387. _this.beta = beta;
  48388. _this.radius = radius;
  48389. _this.getViewMatrix();
  48390. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48391. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48392. return _this;
  48393. }
  48394. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48395. /**
  48396. * Defines the target point of the camera.
  48397. * The camera looks towards it form the radius distance.
  48398. */
  48399. get: function () {
  48400. return this._target;
  48401. },
  48402. set: function (value) {
  48403. this.setTarget(value);
  48404. },
  48405. enumerable: true,
  48406. configurable: true
  48407. });
  48408. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48409. //-- begin properties for backward compatibility for inputs
  48410. /**
  48411. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48412. */
  48413. get: function () {
  48414. var pointers = this.inputs.attached["pointers"];
  48415. if (pointers)
  48416. return pointers.angularSensibilityX;
  48417. return 0;
  48418. },
  48419. set: function (value) {
  48420. var pointers = this.inputs.attached["pointers"];
  48421. if (pointers) {
  48422. pointers.angularSensibilityX = value;
  48423. }
  48424. },
  48425. enumerable: true,
  48426. configurable: true
  48427. });
  48428. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48429. /**
  48430. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48431. */
  48432. get: function () {
  48433. var pointers = this.inputs.attached["pointers"];
  48434. if (pointers)
  48435. return pointers.angularSensibilityY;
  48436. return 0;
  48437. },
  48438. set: function (value) {
  48439. var pointers = this.inputs.attached["pointers"];
  48440. if (pointers) {
  48441. pointers.angularSensibilityY = value;
  48442. }
  48443. },
  48444. enumerable: true,
  48445. configurable: true
  48446. });
  48447. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48448. /**
  48449. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48450. */
  48451. get: function () {
  48452. var pointers = this.inputs.attached["pointers"];
  48453. if (pointers)
  48454. return pointers.pinchPrecision;
  48455. return 0;
  48456. },
  48457. set: function (value) {
  48458. var pointers = this.inputs.attached["pointers"];
  48459. if (pointers) {
  48460. pointers.pinchPrecision = value;
  48461. }
  48462. },
  48463. enumerable: true,
  48464. configurable: true
  48465. });
  48466. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48467. /**
  48468. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48469. * It will be used instead of pinchDeltaPrecision if different from 0.
  48470. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48471. */
  48472. get: function () {
  48473. var pointers = this.inputs.attached["pointers"];
  48474. if (pointers)
  48475. return pointers.pinchDeltaPercentage;
  48476. return 0;
  48477. },
  48478. set: function (value) {
  48479. var pointers = this.inputs.attached["pointers"];
  48480. if (pointers) {
  48481. pointers.pinchDeltaPercentage = value;
  48482. }
  48483. },
  48484. enumerable: true,
  48485. configurable: true
  48486. });
  48487. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48488. /**
  48489. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48490. */
  48491. get: function () {
  48492. var pointers = this.inputs.attached["pointers"];
  48493. if (pointers)
  48494. return pointers.panningSensibility;
  48495. return 0;
  48496. },
  48497. set: function (value) {
  48498. var pointers = this.inputs.attached["pointers"];
  48499. if (pointers) {
  48500. pointers.panningSensibility = value;
  48501. }
  48502. },
  48503. enumerable: true,
  48504. configurable: true
  48505. });
  48506. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48507. /**
  48508. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48509. */
  48510. get: function () {
  48511. var keyboard = this.inputs.attached["keyboard"];
  48512. if (keyboard)
  48513. return keyboard.keysUp;
  48514. return [];
  48515. },
  48516. set: function (value) {
  48517. var keyboard = this.inputs.attached["keyboard"];
  48518. if (keyboard)
  48519. keyboard.keysUp = value;
  48520. },
  48521. enumerable: true,
  48522. configurable: true
  48523. });
  48524. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48525. /**
  48526. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48527. */
  48528. get: function () {
  48529. var keyboard = this.inputs.attached["keyboard"];
  48530. if (keyboard)
  48531. return keyboard.keysDown;
  48532. return [];
  48533. },
  48534. set: function (value) {
  48535. var keyboard = this.inputs.attached["keyboard"];
  48536. if (keyboard)
  48537. keyboard.keysDown = value;
  48538. },
  48539. enumerable: true,
  48540. configurable: true
  48541. });
  48542. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48543. /**
  48544. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48545. */
  48546. get: function () {
  48547. var keyboard = this.inputs.attached["keyboard"];
  48548. if (keyboard)
  48549. return keyboard.keysLeft;
  48550. return [];
  48551. },
  48552. set: function (value) {
  48553. var keyboard = this.inputs.attached["keyboard"];
  48554. if (keyboard)
  48555. keyboard.keysLeft = value;
  48556. },
  48557. enumerable: true,
  48558. configurable: true
  48559. });
  48560. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48561. /**
  48562. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48563. */
  48564. get: function () {
  48565. var keyboard = this.inputs.attached["keyboard"];
  48566. if (keyboard)
  48567. return keyboard.keysRight;
  48568. return [];
  48569. },
  48570. set: function (value) {
  48571. var keyboard = this.inputs.attached["keyboard"];
  48572. if (keyboard)
  48573. keyboard.keysRight = value;
  48574. },
  48575. enumerable: true,
  48576. configurable: true
  48577. });
  48578. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48579. /**
  48580. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48581. */
  48582. get: function () {
  48583. var mousewheel = this.inputs.attached["mousewheel"];
  48584. if (mousewheel)
  48585. return mousewheel.wheelPrecision;
  48586. return 0;
  48587. },
  48588. set: function (value) {
  48589. var mousewheel = this.inputs.attached["mousewheel"];
  48590. if (mousewheel)
  48591. mousewheel.wheelPrecision = value;
  48592. },
  48593. enumerable: true,
  48594. configurable: true
  48595. });
  48596. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48597. /**
  48598. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48599. * It will be used instead of pinchDeltaPrecision if different from 0.
  48600. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48601. */
  48602. get: function () {
  48603. var mousewheel = this.inputs.attached["mousewheel"];
  48604. if (mousewheel)
  48605. return mousewheel.wheelDeltaPercentage;
  48606. return 0;
  48607. },
  48608. set: function (value) {
  48609. var mousewheel = this.inputs.attached["mousewheel"];
  48610. if (mousewheel)
  48611. mousewheel.wheelDeltaPercentage = value;
  48612. },
  48613. enumerable: true,
  48614. configurable: true
  48615. });
  48616. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48617. /**
  48618. * Gets the bouncing behavior of the camera if it has been enabled.
  48619. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48620. */
  48621. get: function () {
  48622. return this._bouncingBehavior;
  48623. },
  48624. enumerable: true,
  48625. configurable: true
  48626. });
  48627. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48628. /**
  48629. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48630. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48631. */
  48632. get: function () {
  48633. return this._bouncingBehavior != null;
  48634. },
  48635. set: function (value) {
  48636. if (value === this.useBouncingBehavior) {
  48637. return;
  48638. }
  48639. if (value) {
  48640. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48641. this.addBehavior(this._bouncingBehavior);
  48642. }
  48643. else if (this._bouncingBehavior) {
  48644. this.removeBehavior(this._bouncingBehavior);
  48645. this._bouncingBehavior = null;
  48646. }
  48647. },
  48648. enumerable: true,
  48649. configurable: true
  48650. });
  48651. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48652. /**
  48653. * Gets the framing behavior of the camera if it has been enabled.
  48654. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48655. */
  48656. get: function () {
  48657. return this._framingBehavior;
  48658. },
  48659. enumerable: true,
  48660. configurable: true
  48661. });
  48662. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48663. /**
  48664. * Defines if the framing behavior of the camera is enabled on the camera.
  48665. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48666. */
  48667. get: function () {
  48668. return this._framingBehavior != null;
  48669. },
  48670. set: function (value) {
  48671. if (value === this.useFramingBehavior) {
  48672. return;
  48673. }
  48674. if (value) {
  48675. this._framingBehavior = new BABYLON.FramingBehavior();
  48676. this.addBehavior(this._framingBehavior);
  48677. }
  48678. else if (this._framingBehavior) {
  48679. this.removeBehavior(this._framingBehavior);
  48680. this._framingBehavior = null;
  48681. }
  48682. },
  48683. enumerable: true,
  48684. configurable: true
  48685. });
  48686. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48687. /**
  48688. * Gets the auto rotation behavior of the camera if it has been enabled.
  48689. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48690. */
  48691. get: function () {
  48692. return this._autoRotationBehavior;
  48693. },
  48694. enumerable: true,
  48695. configurable: true
  48696. });
  48697. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48698. /**
  48699. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48700. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48701. */
  48702. get: function () {
  48703. return this._autoRotationBehavior != null;
  48704. },
  48705. set: function (value) {
  48706. if (value === this.useAutoRotationBehavior) {
  48707. return;
  48708. }
  48709. if (value) {
  48710. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48711. this.addBehavior(this._autoRotationBehavior);
  48712. }
  48713. else if (this._autoRotationBehavior) {
  48714. this.removeBehavior(this._autoRotationBehavior);
  48715. this._autoRotationBehavior = null;
  48716. }
  48717. },
  48718. enumerable: true,
  48719. configurable: true
  48720. });
  48721. // Cache
  48722. /** @hidden */
  48723. ArcRotateCamera.prototype._initCache = function () {
  48724. _super.prototype._initCache.call(this);
  48725. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48726. this._cache.alpha = undefined;
  48727. this._cache.beta = undefined;
  48728. this._cache.radius = undefined;
  48729. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48730. };
  48731. /** @hidden */
  48732. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48733. if (!ignoreParentClass) {
  48734. _super.prototype._updateCache.call(this);
  48735. }
  48736. this._cache._target.copyFrom(this._getTargetPosition());
  48737. this._cache.alpha = this.alpha;
  48738. this._cache.beta = this.beta;
  48739. this._cache.radius = this.radius;
  48740. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48741. };
  48742. ArcRotateCamera.prototype._getTargetPosition = function () {
  48743. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48744. var pos = this._targetHost.getAbsolutePosition();
  48745. if (this._targetBoundingCenter) {
  48746. pos.addToRef(this._targetBoundingCenter, this._target);
  48747. }
  48748. else {
  48749. this._target.copyFrom(pos);
  48750. }
  48751. }
  48752. var lockedTargetPosition = this._getLockedTargetPosition();
  48753. if (lockedTargetPosition) {
  48754. return lockedTargetPosition;
  48755. }
  48756. return this._target;
  48757. };
  48758. /**
  48759. * Stores the current state of the camera (alpha, beta, radius and target)
  48760. * @returns the camera itself
  48761. */
  48762. ArcRotateCamera.prototype.storeState = function () {
  48763. this._storedAlpha = this.alpha;
  48764. this._storedBeta = this.beta;
  48765. this._storedRadius = this.radius;
  48766. this._storedTarget = this._getTargetPosition().clone();
  48767. return _super.prototype.storeState.call(this);
  48768. };
  48769. /**
  48770. * @hidden
  48771. * Restored camera state. You must call storeState() first
  48772. */
  48773. ArcRotateCamera.prototype._restoreStateValues = function () {
  48774. if (!_super.prototype._restoreStateValues.call(this)) {
  48775. return false;
  48776. }
  48777. this.alpha = this._storedAlpha;
  48778. this.beta = this._storedBeta;
  48779. this.radius = this._storedRadius;
  48780. this.setTarget(this._storedTarget.clone());
  48781. this.inertialAlphaOffset = 0;
  48782. this.inertialBetaOffset = 0;
  48783. this.inertialRadiusOffset = 0;
  48784. this.inertialPanningX = 0;
  48785. this.inertialPanningY = 0;
  48786. return true;
  48787. };
  48788. // Synchronized
  48789. /** @hidden */
  48790. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48791. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48792. return false;
  48793. return this._cache._target.equals(this._getTargetPosition())
  48794. && this._cache.alpha === this.alpha
  48795. && this._cache.beta === this.beta
  48796. && this._cache.radius === this.radius
  48797. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48798. };
  48799. /**
  48800. * Attached controls to the current camera.
  48801. * @param element Defines the element the controls should be listened from
  48802. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48803. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48804. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48805. */
  48806. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48807. var _this = this;
  48808. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48809. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48810. this._useCtrlForPanning = useCtrlForPanning;
  48811. this._panningMouseButton = panningMouseButton;
  48812. this.inputs.attachElement(element, noPreventDefault);
  48813. this._reset = function () {
  48814. _this.inertialAlphaOffset = 0;
  48815. _this.inertialBetaOffset = 0;
  48816. _this.inertialRadiusOffset = 0;
  48817. _this.inertialPanningX = 0;
  48818. _this.inertialPanningY = 0;
  48819. };
  48820. };
  48821. /**
  48822. * Detach the current controls from the camera.
  48823. * The camera will stop reacting to inputs.
  48824. * @param element Defines the element to stop listening the inputs from
  48825. */
  48826. ArcRotateCamera.prototype.detachControl = function (element) {
  48827. this.inputs.detachElement(element);
  48828. if (this._reset) {
  48829. this._reset();
  48830. }
  48831. };
  48832. /** @hidden */
  48833. ArcRotateCamera.prototype._checkInputs = function () {
  48834. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48835. if (this._collisionTriggered) {
  48836. return;
  48837. }
  48838. this.inputs.checkInputs();
  48839. // Inertia
  48840. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48841. var inertialAlphaOffset = this.inertialAlphaOffset;
  48842. if (this.beta <= 0)
  48843. inertialAlphaOffset *= -1;
  48844. if (this.getScene().useRightHandedSystem)
  48845. inertialAlphaOffset *= -1;
  48846. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48847. inertialAlphaOffset *= -1;
  48848. this.alpha += inertialAlphaOffset;
  48849. this.beta += this.inertialBetaOffset;
  48850. this.radius -= this.inertialRadiusOffset;
  48851. this.inertialAlphaOffset *= this.inertia;
  48852. this.inertialBetaOffset *= this.inertia;
  48853. this.inertialRadiusOffset *= this.inertia;
  48854. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48855. this.inertialAlphaOffset = 0;
  48856. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48857. this.inertialBetaOffset = 0;
  48858. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48859. this.inertialRadiusOffset = 0;
  48860. }
  48861. // Panning inertia
  48862. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48863. if (!this._localDirection) {
  48864. this._localDirection = BABYLON.Vector3.Zero();
  48865. this._transformedDirection = BABYLON.Vector3.Zero();
  48866. }
  48867. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48868. this._localDirection.multiplyInPlace(this.panningAxis);
  48869. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48870. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48871. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48872. if (!this.panningAxis.y) {
  48873. this._transformedDirection.y = 0;
  48874. }
  48875. if (!this._targetHost) {
  48876. if (this.panningDistanceLimit) {
  48877. this._transformedDirection.addInPlace(this._target);
  48878. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48879. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48880. this._target.copyFrom(this._transformedDirection);
  48881. }
  48882. }
  48883. else {
  48884. this._target.addInPlace(this._transformedDirection);
  48885. }
  48886. }
  48887. this.inertialPanningX *= this.panningInertia;
  48888. this.inertialPanningY *= this.panningInertia;
  48889. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48890. this.inertialPanningX = 0;
  48891. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48892. this.inertialPanningY = 0;
  48893. }
  48894. // Limits
  48895. this._checkLimits();
  48896. _super.prototype._checkInputs.call(this);
  48897. };
  48898. ArcRotateCamera.prototype._checkLimits = function () {
  48899. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48900. if (this.allowUpsideDown && this.beta > Math.PI) {
  48901. this.beta = this.beta - (2 * Math.PI);
  48902. }
  48903. }
  48904. else {
  48905. if (this.beta < this.lowerBetaLimit) {
  48906. this.beta = this.lowerBetaLimit;
  48907. }
  48908. }
  48909. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48910. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48911. this.beta = this.beta + (2 * Math.PI);
  48912. }
  48913. }
  48914. else {
  48915. if (this.beta > this.upperBetaLimit) {
  48916. this.beta = this.upperBetaLimit;
  48917. }
  48918. }
  48919. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48920. this.alpha = this.lowerAlphaLimit;
  48921. }
  48922. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48923. this.alpha = this.upperAlphaLimit;
  48924. }
  48925. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48926. this.radius = this.lowerRadiusLimit;
  48927. }
  48928. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48929. this.radius = this.upperRadiusLimit;
  48930. }
  48931. };
  48932. /**
  48933. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48934. */
  48935. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48936. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48937. this.radius = this._computationVector.length();
  48938. if (this.radius === 0) {
  48939. this.radius = 0.0001; // Just to avoid division by zero
  48940. }
  48941. // Alpha
  48942. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48943. if (this._computationVector.z < 0) {
  48944. this.alpha = 2 * Math.PI - this.alpha;
  48945. }
  48946. // Beta
  48947. this.beta = Math.acos(this._computationVector.y / this.radius);
  48948. this._checkLimits();
  48949. };
  48950. /**
  48951. * Use a position to define the current camera related information like aplha, beta and radius
  48952. * @param position Defines the position to set the camera at
  48953. */
  48954. ArcRotateCamera.prototype.setPosition = function (position) {
  48955. if (this.position.equals(position)) {
  48956. return;
  48957. }
  48958. this.position.copyFrom(position);
  48959. this.rebuildAnglesAndRadius();
  48960. };
  48961. /**
  48962. * Defines the target the camera should look at.
  48963. * This will automatically adapt alpha beta and radius to fit within the new target.
  48964. * @param target Defines the new target as a Vector or a mesh
  48965. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48966. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48967. */
  48968. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48969. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48970. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48971. if (target.getBoundingInfo) {
  48972. if (toBoundingCenter) {
  48973. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48974. }
  48975. else {
  48976. this._targetBoundingCenter = null;
  48977. }
  48978. this._targetHost = target;
  48979. this._target = this._getTargetPosition();
  48980. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48981. }
  48982. else {
  48983. var newTarget = target;
  48984. var currentTarget = this._getTargetPosition();
  48985. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48986. return;
  48987. }
  48988. this._targetHost = null;
  48989. this._target = newTarget;
  48990. this._targetBoundingCenter = null;
  48991. this.onMeshTargetChangedObservable.notifyObservers(null);
  48992. }
  48993. this.rebuildAnglesAndRadius();
  48994. };
  48995. /** @hidden */
  48996. ArcRotateCamera.prototype._getViewMatrix = function () {
  48997. // Compute
  48998. var cosa = Math.cos(this.alpha);
  48999. var sina = Math.sin(this.alpha);
  49000. var cosb = Math.cos(this.beta);
  49001. var sinb = Math.sin(this.beta);
  49002. if (sinb === 0) {
  49003. sinb = 0.0001;
  49004. }
  49005. var target = this._getTargetPosition();
  49006. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49007. target.addToRef(this._computationVector, this._newPosition);
  49008. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49009. if (!this._collider) {
  49010. this._collider = new BABYLON.Collider();
  49011. }
  49012. this._collider._radius = this.collisionRadius;
  49013. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49014. this._collisionTriggered = true;
  49015. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49016. }
  49017. else {
  49018. this.position.copyFrom(this._newPosition);
  49019. var up = this.upVector;
  49020. if (this.allowUpsideDown && sinb < 0) {
  49021. up = up.clone();
  49022. up = up.negate();
  49023. }
  49024. this._computeViewMatrix(this.position, target, up);
  49025. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49026. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49027. }
  49028. this._currentTarget = target;
  49029. return this._viewMatrix;
  49030. };
  49031. /**
  49032. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49033. * @param meshes Defines the mesh to zoom on
  49034. * @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)
  49035. */
  49036. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49037. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49038. meshes = meshes || this.getScene().meshes;
  49039. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49040. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49041. this.radius = distance * this.zoomOnFactor;
  49042. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49043. };
  49044. /**
  49045. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49046. * The target will be changed but the radius
  49047. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49048. * @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)
  49049. */
  49050. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49051. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49052. var meshesOrMinMaxVector;
  49053. var distance;
  49054. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49055. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49056. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49057. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49058. }
  49059. else { //minMaxVector and distance
  49060. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49061. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49062. distance = minMaxVectorAndDistance.distance;
  49063. }
  49064. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49065. if (!doNotUpdateMaxZ) {
  49066. this.maxZ = distance * 2;
  49067. }
  49068. };
  49069. /**
  49070. * @override
  49071. * Override Camera.createRigCamera
  49072. */
  49073. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49074. var alphaShift = 0;
  49075. switch (this.cameraRigMode) {
  49076. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49078. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49079. case BABYLON.Camera.RIG_MODE_VR:
  49080. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49081. break;
  49082. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49083. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49084. break;
  49085. }
  49086. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49087. rigCam._cameraRigParams = {};
  49088. return rigCam;
  49089. };
  49090. /**
  49091. * @hidden
  49092. * @override
  49093. * Override Camera._updateRigCameras
  49094. */
  49095. ArcRotateCamera.prototype._updateRigCameras = function () {
  49096. var camLeft = this._rigCameras[0];
  49097. var camRight = this._rigCameras[1];
  49098. camLeft.beta = camRight.beta = this.beta;
  49099. camLeft.radius = camRight.radius = this.radius;
  49100. switch (this.cameraRigMode) {
  49101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49104. case BABYLON.Camera.RIG_MODE_VR:
  49105. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49106. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49107. break;
  49108. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49109. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49110. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49111. break;
  49112. }
  49113. _super.prototype._updateRigCameras.call(this);
  49114. };
  49115. /**
  49116. * Destroy the camera and release the current resources hold by it.
  49117. */
  49118. ArcRotateCamera.prototype.dispose = function () {
  49119. this.inputs.clear();
  49120. _super.prototype.dispose.call(this);
  49121. };
  49122. /**
  49123. * Gets the current object class name.
  49124. * @return the class name
  49125. */
  49126. ArcRotateCamera.prototype.getClassName = function () {
  49127. return "ArcRotateCamera";
  49128. };
  49129. __decorate([
  49130. BABYLON.serialize()
  49131. ], ArcRotateCamera.prototype, "alpha", void 0);
  49132. __decorate([
  49133. BABYLON.serialize()
  49134. ], ArcRotateCamera.prototype, "beta", void 0);
  49135. __decorate([
  49136. BABYLON.serialize()
  49137. ], ArcRotateCamera.prototype, "radius", void 0);
  49138. __decorate([
  49139. BABYLON.serializeAsVector3("target")
  49140. ], ArcRotateCamera.prototype, "_target", void 0);
  49141. __decorate([
  49142. BABYLON.serialize()
  49143. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49144. __decorate([
  49145. BABYLON.serialize()
  49146. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49147. __decorate([
  49148. BABYLON.serialize()
  49149. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49150. __decorate([
  49151. BABYLON.serialize()
  49152. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49153. __decorate([
  49154. BABYLON.serialize()
  49155. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49156. __decorate([
  49157. BABYLON.serialize()
  49158. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49159. __decorate([
  49160. BABYLON.serialize()
  49161. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49162. __decorate([
  49163. BABYLON.serialize()
  49164. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49165. __decorate([
  49166. BABYLON.serialize()
  49167. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49171. __decorate([
  49172. BABYLON.serialize()
  49173. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49174. __decorate([
  49175. BABYLON.serialize()
  49176. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49177. __decorate([
  49178. BABYLON.serialize()
  49179. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49180. __decorate([
  49181. BABYLON.serializeAsVector3()
  49182. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49183. __decorate([
  49184. BABYLON.serialize()
  49185. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49186. __decorate([
  49187. BABYLON.serialize()
  49188. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49189. __decorate([
  49190. BABYLON.serialize()
  49191. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49192. __decorate([
  49193. BABYLON.serialize()
  49194. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49195. __decorate([
  49196. BABYLON.serialize()
  49197. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49198. return ArcRotateCamera;
  49199. }(BABYLON.TargetCamera));
  49200. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49201. })(BABYLON || (BABYLON = {}));
  49202. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49203. var BABYLON;
  49204. (function (BABYLON) {
  49205. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49206. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49207. });
  49208. /**
  49209. * The HemisphericLight simulates the ambient environment light,
  49210. * so the passed direction is the light reflection direction, not the incoming direction.
  49211. */
  49212. var HemisphericLight = /** @class */ (function (_super) {
  49213. __extends(HemisphericLight, _super);
  49214. /**
  49215. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49216. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49217. * The HemisphericLight can't cast shadows.
  49218. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49219. * @param name The friendly name of the light
  49220. * @param direction The direction of the light reflection
  49221. * @param scene The scene the light belongs to
  49222. */
  49223. function HemisphericLight(name, direction, scene) {
  49224. var _this = _super.call(this, name, scene) || this;
  49225. /**
  49226. * The groundColor is the light in the opposite direction to the one specified during creation.
  49227. * 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.
  49228. */
  49229. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49230. _this.direction = direction || BABYLON.Vector3.Up();
  49231. return _this;
  49232. }
  49233. HemisphericLight.prototype._buildUniformLayout = function () {
  49234. this._uniformBuffer.addUniform("vLightData", 4);
  49235. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49236. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49237. this._uniformBuffer.addUniform("vLightGround", 3);
  49238. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49239. this._uniformBuffer.addUniform("depthValues", 2);
  49240. this._uniformBuffer.create();
  49241. };
  49242. /**
  49243. * Returns the string "HemisphericLight".
  49244. * @return The class name
  49245. */
  49246. HemisphericLight.prototype.getClassName = function () {
  49247. return "HemisphericLight";
  49248. };
  49249. /**
  49250. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49251. * Returns the updated direction.
  49252. * @param target The target the direction should point to
  49253. * @return The computed direction
  49254. */
  49255. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49256. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49257. return this.direction;
  49258. };
  49259. /**
  49260. * Returns the shadow generator associated to the light.
  49261. * @returns Always null for hemispheric lights because it does not support shadows.
  49262. */
  49263. HemisphericLight.prototype.getShadowGenerator = function () {
  49264. return null;
  49265. };
  49266. /**
  49267. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49268. * @param effect The effect to update
  49269. * @param lightIndex The index of the light in the effect to update
  49270. * @returns The hemispheric light
  49271. */
  49272. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49273. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49274. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49275. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49276. return this;
  49277. };
  49278. /**
  49279. * Computes the world matrix of the node
  49280. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49281. * @param useWasUpdatedFlag defines a reserved property
  49282. * @returns the world matrix
  49283. */
  49284. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49285. if (!this._worldMatrix) {
  49286. this._worldMatrix = BABYLON.Matrix.Identity();
  49287. }
  49288. return this._worldMatrix;
  49289. };
  49290. /**
  49291. * Returns the integer 3.
  49292. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49293. */
  49294. HemisphericLight.prototype.getTypeID = function () {
  49295. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49296. };
  49297. /**
  49298. * Prepares the list of defines specific to the light type.
  49299. * @param defines the list of defines
  49300. * @param lightIndex defines the index of the light for the effect
  49301. */
  49302. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49303. defines["HEMILIGHT" + lightIndex] = true;
  49304. };
  49305. __decorate([
  49306. BABYLON.serializeAsColor3()
  49307. ], HemisphericLight.prototype, "groundColor", void 0);
  49308. __decorate([
  49309. BABYLON.serializeAsVector3()
  49310. ], HemisphericLight.prototype, "direction", void 0);
  49311. return HemisphericLight;
  49312. }(BABYLON.Light));
  49313. BABYLON.HemisphericLight = HemisphericLight;
  49314. })(BABYLON || (BABYLON = {}));
  49315. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49316. var BABYLON;
  49317. (function (BABYLON) {
  49318. /**
  49319. * Base implementation IShadowLight
  49320. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49321. */
  49322. var ShadowLight = /** @class */ (function (_super) {
  49323. __extends(ShadowLight, _super);
  49324. function ShadowLight() {
  49325. var _this = _super !== null && _super.apply(this, arguments) || this;
  49326. _this._needProjectionMatrixCompute = true;
  49327. return _this;
  49328. }
  49329. ShadowLight.prototype._setPosition = function (value) {
  49330. this._position = value;
  49331. };
  49332. Object.defineProperty(ShadowLight.prototype, "position", {
  49333. /**
  49334. * Sets the position the shadow will be casted from. Also use as the light position for both
  49335. * point and spot lights.
  49336. */
  49337. get: function () {
  49338. return this._position;
  49339. },
  49340. /**
  49341. * Sets the position the shadow will be casted from. Also use as the light position for both
  49342. * point and spot lights.
  49343. */
  49344. set: function (value) {
  49345. this._setPosition(value);
  49346. },
  49347. enumerable: true,
  49348. configurable: true
  49349. });
  49350. ShadowLight.prototype._setDirection = function (value) {
  49351. this._direction = value;
  49352. };
  49353. Object.defineProperty(ShadowLight.prototype, "direction", {
  49354. /**
  49355. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49356. * Also use as the light direction on spot and directional lights.
  49357. */
  49358. get: function () {
  49359. return this._direction;
  49360. },
  49361. /**
  49362. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49363. * Also use as the light direction on spot and directional lights.
  49364. */
  49365. set: function (value) {
  49366. this._setDirection(value);
  49367. },
  49368. enumerable: true,
  49369. configurable: true
  49370. });
  49371. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49372. /**
  49373. * Gets the shadow projection clipping minimum z value.
  49374. */
  49375. get: function () {
  49376. return this._shadowMinZ;
  49377. },
  49378. /**
  49379. * Sets the shadow projection clipping minimum z value.
  49380. */
  49381. set: function (value) {
  49382. this._shadowMinZ = value;
  49383. this.forceProjectionMatrixCompute();
  49384. },
  49385. enumerable: true,
  49386. configurable: true
  49387. });
  49388. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49389. /**
  49390. * Sets the shadow projection clipping maximum z value.
  49391. */
  49392. get: function () {
  49393. return this._shadowMaxZ;
  49394. },
  49395. /**
  49396. * Gets the shadow projection clipping maximum z value.
  49397. */
  49398. set: function (value) {
  49399. this._shadowMaxZ = value;
  49400. this.forceProjectionMatrixCompute();
  49401. },
  49402. enumerable: true,
  49403. configurable: true
  49404. });
  49405. /**
  49406. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49407. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49408. */
  49409. ShadowLight.prototype.computeTransformedInformation = function () {
  49410. if (this.parent && this.parent.getWorldMatrix) {
  49411. if (!this.transformedPosition) {
  49412. this.transformedPosition = BABYLON.Vector3.Zero();
  49413. }
  49414. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49415. // In case the direction is present.
  49416. if (this.direction) {
  49417. if (!this.transformedDirection) {
  49418. this.transformedDirection = BABYLON.Vector3.Zero();
  49419. }
  49420. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49421. }
  49422. return true;
  49423. }
  49424. return false;
  49425. };
  49426. /**
  49427. * Return the depth scale used for the shadow map.
  49428. * @returns the depth scale.
  49429. */
  49430. ShadowLight.prototype.getDepthScale = function () {
  49431. return 50.0;
  49432. };
  49433. /**
  49434. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49435. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49436. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49437. */
  49438. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49439. return this.transformedDirection ? this.transformedDirection : this.direction;
  49440. };
  49441. /**
  49442. * Returns the ShadowLight absolute position in the World.
  49443. * @returns the position vector in world space
  49444. */
  49445. ShadowLight.prototype.getAbsolutePosition = function () {
  49446. return this.transformedPosition ? this.transformedPosition : this.position;
  49447. };
  49448. /**
  49449. * Sets the ShadowLight direction toward the passed target.
  49450. * @param target The point tot target in local space
  49451. * @returns the updated ShadowLight direction
  49452. */
  49453. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49454. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49455. return this.direction;
  49456. };
  49457. /**
  49458. * Returns the light rotation in euler definition.
  49459. * @returns the x y z rotation in local space.
  49460. */
  49461. ShadowLight.prototype.getRotation = function () {
  49462. this.direction.normalize();
  49463. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49464. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49465. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49466. };
  49467. /**
  49468. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49469. * @returns true if a cube texture needs to be use
  49470. */
  49471. ShadowLight.prototype.needCube = function () {
  49472. return false;
  49473. };
  49474. /**
  49475. * Detects if the projection matrix requires to be recomputed this frame.
  49476. * @returns true if it requires to be recomputed otherwise, false.
  49477. */
  49478. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49479. return this._needProjectionMatrixCompute;
  49480. };
  49481. /**
  49482. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49483. */
  49484. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49485. this._needProjectionMatrixCompute = true;
  49486. };
  49487. /** @hidden */
  49488. ShadowLight.prototype._initCache = function () {
  49489. _super.prototype._initCache.call(this);
  49490. this._cache.position = BABYLON.Vector3.Zero();
  49491. };
  49492. /** @hidden */
  49493. ShadowLight.prototype._isSynchronized = function () {
  49494. if (!this._cache.position.equals(this.position))
  49495. return false;
  49496. return true;
  49497. };
  49498. /**
  49499. * Computes the world matrix of the node
  49500. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49501. * @returns the world matrix
  49502. */
  49503. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49504. if (!force && this.isSynchronized()) {
  49505. this._currentRenderId = this.getScene().getRenderId();
  49506. return this._worldMatrix;
  49507. }
  49508. this._updateCache();
  49509. this._cache.position.copyFrom(this.position);
  49510. if (!this._worldMatrix) {
  49511. this._worldMatrix = BABYLON.Matrix.Identity();
  49512. }
  49513. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49514. if (this.parent && this.parent.getWorldMatrix) {
  49515. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49516. this._markSyncedWithParent();
  49517. }
  49518. // Cache the determinant
  49519. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49520. return this._worldMatrix;
  49521. };
  49522. /**
  49523. * Gets the minZ used for shadow according to both the scene and the light.
  49524. * @param activeCamera The camera we are returning the min for
  49525. * @returns the depth min z
  49526. */
  49527. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49528. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49529. };
  49530. /**
  49531. * Gets the maxZ used for shadow according to both the scene and the light.
  49532. * @param activeCamera The camera we are returning the max for
  49533. * @returns the depth max z
  49534. */
  49535. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49536. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49537. };
  49538. /**
  49539. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49540. * @param matrix The materix to updated with the projection information
  49541. * @param viewMatrix The transform matrix of the light
  49542. * @param renderList The list of mesh to render in the map
  49543. * @returns The current light
  49544. */
  49545. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49546. if (this.customProjectionMatrixBuilder) {
  49547. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49548. }
  49549. else {
  49550. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49551. }
  49552. return this;
  49553. };
  49554. __decorate([
  49555. BABYLON.serializeAsVector3()
  49556. ], ShadowLight.prototype, "position", null);
  49557. __decorate([
  49558. BABYLON.serializeAsVector3()
  49559. ], ShadowLight.prototype, "direction", null);
  49560. __decorate([
  49561. BABYLON.serialize()
  49562. ], ShadowLight.prototype, "shadowMinZ", null);
  49563. __decorate([
  49564. BABYLON.serialize()
  49565. ], ShadowLight.prototype, "shadowMaxZ", null);
  49566. return ShadowLight;
  49567. }(BABYLON.Light));
  49568. BABYLON.ShadowLight = ShadowLight;
  49569. })(BABYLON || (BABYLON = {}));
  49570. //# sourceMappingURL=babylon.shadowLight.js.map
  49571. var BABYLON;
  49572. (function (BABYLON) {
  49573. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49574. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49575. });
  49576. /**
  49577. * A point light is a light defined by an unique point in world space.
  49578. * The light is emitted in every direction from this point.
  49579. * A good example of a point light is a standard light bulb.
  49580. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49581. */
  49582. var PointLight = /** @class */ (function (_super) {
  49583. __extends(PointLight, _super);
  49584. /**
  49585. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49586. * A PointLight emits the light in every direction.
  49587. * It can cast shadows.
  49588. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49589. * ```javascript
  49590. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49591. * ```
  49592. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49593. * @param name The light friendly name
  49594. * @param position The position of the point light in the scene
  49595. * @param scene The scene the lights belongs to
  49596. */
  49597. function PointLight(name, position, scene) {
  49598. var _this = _super.call(this, name, scene) || this;
  49599. _this._shadowAngle = Math.PI / 2;
  49600. _this.position = position;
  49601. return _this;
  49602. }
  49603. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49604. /**
  49605. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49606. * This specifies what angle the shadow will use to be created.
  49607. *
  49608. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49609. */
  49610. get: function () {
  49611. return this._shadowAngle;
  49612. },
  49613. /**
  49614. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49615. * This specifies what angle the shadow will use to be created.
  49616. *
  49617. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49618. */
  49619. set: function (value) {
  49620. this._shadowAngle = value;
  49621. this.forceProjectionMatrixCompute();
  49622. },
  49623. enumerable: true,
  49624. configurable: true
  49625. });
  49626. Object.defineProperty(PointLight.prototype, "direction", {
  49627. /**
  49628. * Gets the direction if it has been set.
  49629. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49630. */
  49631. get: function () {
  49632. return this._direction;
  49633. },
  49634. /**
  49635. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49636. */
  49637. set: function (value) {
  49638. var previousNeedCube = this.needCube();
  49639. this._direction = value;
  49640. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49641. this._shadowGenerator.recreateShadowMap();
  49642. }
  49643. },
  49644. enumerable: true,
  49645. configurable: true
  49646. });
  49647. /**
  49648. * Returns the string "PointLight"
  49649. * @returns the class name
  49650. */
  49651. PointLight.prototype.getClassName = function () {
  49652. return "PointLight";
  49653. };
  49654. /**
  49655. * Returns the integer 0.
  49656. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49657. */
  49658. PointLight.prototype.getTypeID = function () {
  49659. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49660. };
  49661. /**
  49662. * Specifies wether or not the shadowmap should be a cube texture.
  49663. * @returns true if the shadowmap needs to be a cube texture.
  49664. */
  49665. PointLight.prototype.needCube = function () {
  49666. return !this.direction;
  49667. };
  49668. /**
  49669. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49670. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49671. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49672. */
  49673. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49674. if (this.direction) {
  49675. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49676. }
  49677. else {
  49678. switch (faceIndex) {
  49679. case 0:
  49680. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49681. case 1:
  49682. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49683. case 2:
  49684. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49685. case 3:
  49686. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49687. case 4:
  49688. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49689. case 5:
  49690. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49691. }
  49692. }
  49693. return BABYLON.Vector3.Zero();
  49694. };
  49695. /**
  49696. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49697. * - fov = PI / 2
  49698. * - aspect ratio : 1.0
  49699. * - z-near and far equal to the active camera minZ and maxZ.
  49700. * Returns the PointLight.
  49701. */
  49702. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49703. var activeCamera = this.getScene().activeCamera;
  49704. if (!activeCamera) {
  49705. return;
  49706. }
  49707. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49708. };
  49709. PointLight.prototype._buildUniformLayout = function () {
  49710. this._uniformBuffer.addUniform("vLightData", 4);
  49711. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49712. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49713. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49714. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49715. this._uniformBuffer.addUniform("depthValues", 2);
  49716. this._uniformBuffer.create();
  49717. };
  49718. /**
  49719. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49720. * @param effect The effect to update
  49721. * @param lightIndex The index of the light in the effect to update
  49722. * @returns The point light
  49723. */
  49724. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49725. if (this.computeTransformedInformation()) {
  49726. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49727. }
  49728. else {
  49729. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49730. }
  49731. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49732. return this;
  49733. };
  49734. /**
  49735. * Prepares the list of defines specific to the light type.
  49736. * @param defines the list of defines
  49737. * @param lightIndex defines the index of the light for the effect
  49738. */
  49739. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49740. defines["POINTLIGHT" + lightIndex] = true;
  49741. };
  49742. __decorate([
  49743. BABYLON.serialize()
  49744. ], PointLight.prototype, "shadowAngle", null);
  49745. return PointLight;
  49746. }(BABYLON.ShadowLight));
  49747. BABYLON.PointLight = PointLight;
  49748. })(BABYLON || (BABYLON = {}));
  49749. //# sourceMappingURL=babylon.pointLight.js.map
  49750. var BABYLON;
  49751. (function (BABYLON) {
  49752. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49753. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49754. });
  49755. /**
  49756. * A directional light is defined by a direction (what a surprise!).
  49757. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49758. * 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.
  49759. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49760. */
  49761. var DirectionalLight = /** @class */ (function (_super) {
  49762. __extends(DirectionalLight, _super);
  49763. /**
  49764. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49765. * The directional light is emitted from everywhere in the given direction.
  49766. * It can cast shadows.
  49767. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49768. * @param name The friendly name of the light
  49769. * @param direction The direction of the light
  49770. * @param scene The scene the light belongs to
  49771. */
  49772. function DirectionalLight(name, direction, scene) {
  49773. var _this = _super.call(this, name, scene) || this;
  49774. _this._shadowFrustumSize = 0;
  49775. _this._shadowOrthoScale = 0.1;
  49776. /**
  49777. * Automatically compute the projection matrix to best fit (including all the casters)
  49778. * on each frame.
  49779. */
  49780. _this.autoUpdateExtends = true;
  49781. // Cache
  49782. _this._orthoLeft = Number.MAX_VALUE;
  49783. _this._orthoRight = Number.MIN_VALUE;
  49784. _this._orthoTop = Number.MIN_VALUE;
  49785. _this._orthoBottom = Number.MAX_VALUE;
  49786. _this.position = direction.scale(-1.0);
  49787. _this.direction = direction;
  49788. return _this;
  49789. }
  49790. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49791. /**
  49792. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49793. */
  49794. get: function () {
  49795. return this._shadowFrustumSize;
  49796. },
  49797. /**
  49798. * Specifies a fix frustum size for the shadow generation.
  49799. */
  49800. set: function (value) {
  49801. this._shadowFrustumSize = value;
  49802. this.forceProjectionMatrixCompute();
  49803. },
  49804. enumerable: true,
  49805. configurable: true
  49806. });
  49807. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49808. /**
  49809. * Gets the shadow projection scale against the optimal computed one.
  49810. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49811. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49812. */
  49813. get: function () {
  49814. return this._shadowOrthoScale;
  49815. },
  49816. /**
  49817. * Sets the shadow projection scale against the optimal computed one.
  49818. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49819. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49820. */
  49821. set: function (value) {
  49822. this._shadowOrthoScale = value;
  49823. this.forceProjectionMatrixCompute();
  49824. },
  49825. enumerable: true,
  49826. configurable: true
  49827. });
  49828. /**
  49829. * Returns the string "DirectionalLight".
  49830. * @return The class name
  49831. */
  49832. DirectionalLight.prototype.getClassName = function () {
  49833. return "DirectionalLight";
  49834. };
  49835. /**
  49836. * Returns the integer 1.
  49837. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49838. */
  49839. DirectionalLight.prototype.getTypeID = function () {
  49840. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49841. };
  49842. /**
  49843. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49844. * Returns the DirectionalLight Shadow projection matrix.
  49845. */
  49846. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49847. if (this.shadowFrustumSize > 0) {
  49848. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49849. }
  49850. else {
  49851. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49852. }
  49853. };
  49854. /**
  49855. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49856. * Returns the DirectionalLight Shadow projection matrix.
  49857. */
  49858. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49859. var activeCamera = this.getScene().activeCamera;
  49860. if (!activeCamera) {
  49861. return;
  49862. }
  49863. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49864. };
  49865. /**
  49866. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49867. * Returns the DirectionalLight Shadow projection matrix.
  49868. */
  49869. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49870. var activeCamera = this.getScene().activeCamera;
  49871. if (!activeCamera) {
  49872. return;
  49873. }
  49874. // Check extends
  49875. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49876. var tempVector3 = BABYLON.Vector3.Zero();
  49877. this._orthoLeft = Number.MAX_VALUE;
  49878. this._orthoRight = Number.MIN_VALUE;
  49879. this._orthoTop = Number.MIN_VALUE;
  49880. this._orthoBottom = Number.MAX_VALUE;
  49881. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49882. var mesh = renderList[meshIndex];
  49883. if (!mesh) {
  49884. continue;
  49885. }
  49886. var boundingInfo = mesh.getBoundingInfo();
  49887. var boundingBox = boundingInfo.boundingBox;
  49888. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49889. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49890. if (tempVector3.x < this._orthoLeft)
  49891. this._orthoLeft = tempVector3.x;
  49892. if (tempVector3.y < this._orthoBottom)
  49893. this._orthoBottom = tempVector3.y;
  49894. if (tempVector3.x > this._orthoRight)
  49895. this._orthoRight = tempVector3.x;
  49896. if (tempVector3.y > this._orthoTop)
  49897. this._orthoTop = tempVector3.y;
  49898. }
  49899. }
  49900. }
  49901. var xOffset = this._orthoRight - this._orthoLeft;
  49902. var yOffset = this._orthoTop - this._orthoBottom;
  49903. 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);
  49904. };
  49905. DirectionalLight.prototype._buildUniformLayout = function () {
  49906. this._uniformBuffer.addUniform("vLightData", 4);
  49907. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49908. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49909. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49910. this._uniformBuffer.addUniform("depthValues", 2);
  49911. this._uniformBuffer.create();
  49912. };
  49913. /**
  49914. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49915. * @param effect The effect to update
  49916. * @param lightIndex The index of the light in the effect to update
  49917. * @returns The directional light
  49918. */
  49919. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49920. if (this.computeTransformedInformation()) {
  49921. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49922. return this;
  49923. }
  49924. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49925. return this;
  49926. };
  49927. /**
  49928. * Gets the minZ used for shadow according to both the scene and the light.
  49929. *
  49930. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49931. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49932. * @param activeCamera The camera we are returning the min for
  49933. * @returns the depth min z
  49934. */
  49935. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49936. return 1;
  49937. };
  49938. /**
  49939. * Gets the maxZ used for shadow according to both the scene and the light.
  49940. *
  49941. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49942. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49943. * @param activeCamera The camera we are returning the max for
  49944. * @returns the depth max z
  49945. */
  49946. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49947. return 1;
  49948. };
  49949. /**
  49950. * Prepares the list of defines specific to the light type.
  49951. * @param defines the list of defines
  49952. * @param lightIndex defines the index of the light for the effect
  49953. */
  49954. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49955. defines["DIRLIGHT" + lightIndex] = true;
  49956. };
  49957. __decorate([
  49958. BABYLON.serialize()
  49959. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49960. __decorate([
  49961. BABYLON.serialize()
  49962. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49963. __decorate([
  49964. BABYLON.serialize()
  49965. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49966. return DirectionalLight;
  49967. }(BABYLON.ShadowLight));
  49968. BABYLON.DirectionalLight = DirectionalLight;
  49969. })(BABYLON || (BABYLON = {}));
  49970. //# sourceMappingURL=babylon.directionalLight.js.map
  49971. var BABYLON;
  49972. (function (BABYLON) {
  49973. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49974. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49975. });
  49976. /**
  49977. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49978. * These values define a cone of light starting from the position, emitting toward the direction.
  49979. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49980. * and the exponent defines the speed of the decay of the light with distance (reach).
  49981. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49982. */
  49983. var SpotLight = /** @class */ (function (_super) {
  49984. __extends(SpotLight, _super);
  49985. /**
  49986. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49987. * It can cast shadows.
  49988. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49989. * @param name The light friendly name
  49990. * @param position The position of the spot light in the scene
  49991. * @param direction The direction of the light in the scene
  49992. * @param angle The cone angle of the light in Radians
  49993. * @param exponent The light decay speed with the distance from the emission spot
  49994. * @param scene The scene the lights belongs to
  49995. */
  49996. function SpotLight(name, position, direction, angle, exponent, scene) {
  49997. var _this = _super.call(this, name, scene) || this;
  49998. _this._innerAngle = 0;
  49999. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50000. _this._projectionTextureLightNear = 1e-6;
  50001. _this._projectionTextureLightFar = 1000.0;
  50002. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50003. _this._projectionTextureViewLightDirty = true;
  50004. _this._projectionTextureProjectionLightDirty = true;
  50005. _this._projectionTextureDirty = true;
  50006. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50007. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50008. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50009. _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);
  50010. _this.position = position;
  50011. _this.direction = direction;
  50012. _this.angle = angle;
  50013. _this.exponent = exponent;
  50014. return _this;
  50015. }
  50016. Object.defineProperty(SpotLight.prototype, "angle", {
  50017. /**
  50018. * Gets the cone angle of the spot light in Radians.
  50019. */
  50020. get: function () {
  50021. return this._angle;
  50022. },
  50023. /**
  50024. * Sets the cone angle of the spot light in Radians.
  50025. */
  50026. set: function (value) {
  50027. this._angle = value;
  50028. this._cosHalfAngle = Math.cos(value * 0.5);
  50029. this._projectionTextureProjectionLightDirty = true;
  50030. this.forceProjectionMatrixCompute();
  50031. this._computeAngleValues();
  50032. },
  50033. enumerable: true,
  50034. configurable: true
  50035. });
  50036. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50037. /**
  50038. * Only used in gltf falloff mode, this defines the angle where
  50039. * the directional falloff will start before cutting at angle which could be seen
  50040. * as outer angle.
  50041. */
  50042. get: function () {
  50043. return this._innerAngle;
  50044. },
  50045. /**
  50046. * Only used in gltf falloff mode, this defines the angle where
  50047. * the directional falloff will start before cutting at angle which could be seen
  50048. * as outer angle.
  50049. */
  50050. set: function (value) {
  50051. this._innerAngle = value;
  50052. this._computeAngleValues();
  50053. },
  50054. enumerable: true,
  50055. configurable: true
  50056. });
  50057. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50058. /**
  50059. * Allows scaling the angle of the light for shadow generation only.
  50060. */
  50061. get: function () {
  50062. return this._shadowAngleScale;
  50063. },
  50064. /**
  50065. * Allows scaling the angle of the light for shadow generation only.
  50066. */
  50067. set: function (value) {
  50068. this._shadowAngleScale = value;
  50069. this.forceProjectionMatrixCompute();
  50070. },
  50071. enumerable: true,
  50072. configurable: true
  50073. });
  50074. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50075. /**
  50076. * Allows reading the projecton texture
  50077. */
  50078. get: function () {
  50079. return this._projectionTextureMatrix;
  50080. },
  50081. enumerable: true,
  50082. configurable: true
  50083. });
  50084. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50085. /**
  50086. * Gets the near clip of the Spotlight for texture projection.
  50087. */
  50088. get: function () {
  50089. return this._projectionTextureLightNear;
  50090. },
  50091. /**
  50092. * Sets the near clip of the Spotlight for texture projection.
  50093. */
  50094. set: function (value) {
  50095. this._projectionTextureLightNear = value;
  50096. this._projectionTextureProjectionLightDirty = true;
  50097. },
  50098. enumerable: true,
  50099. configurable: true
  50100. });
  50101. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50102. /**
  50103. * Gets the far clip of the Spotlight for texture projection.
  50104. */
  50105. get: function () {
  50106. return this._projectionTextureLightFar;
  50107. },
  50108. /**
  50109. * Sets the far clip of the Spotlight for texture projection.
  50110. */
  50111. set: function (value) {
  50112. this._projectionTextureLightFar = value;
  50113. this._projectionTextureProjectionLightDirty = true;
  50114. },
  50115. enumerable: true,
  50116. configurable: true
  50117. });
  50118. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50119. /**
  50120. * Gets the Up vector of the Spotlight for texture projection.
  50121. */
  50122. get: function () {
  50123. return this._projectionTextureUpDirection;
  50124. },
  50125. /**
  50126. * Sets the Up vector of the Spotlight for texture projection.
  50127. */
  50128. set: function (value) {
  50129. this._projectionTextureUpDirection = value;
  50130. this._projectionTextureProjectionLightDirty = true;
  50131. },
  50132. enumerable: true,
  50133. configurable: true
  50134. });
  50135. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50136. /**
  50137. * Gets the projection texture of the light.
  50138. */
  50139. get: function () {
  50140. return this._projectionTexture;
  50141. },
  50142. /**
  50143. * Sets the projection texture of the light.
  50144. */
  50145. set: function (value) {
  50146. this._projectionTexture = value;
  50147. this._projectionTextureDirty = true;
  50148. },
  50149. enumerable: true,
  50150. configurable: true
  50151. });
  50152. /**
  50153. * Returns the string "SpotLight".
  50154. * @returns the class name
  50155. */
  50156. SpotLight.prototype.getClassName = function () {
  50157. return "SpotLight";
  50158. };
  50159. /**
  50160. * Returns the integer 2.
  50161. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50162. */
  50163. SpotLight.prototype.getTypeID = function () {
  50164. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50165. };
  50166. /**
  50167. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50168. */
  50169. SpotLight.prototype._setDirection = function (value) {
  50170. _super.prototype._setDirection.call(this, value);
  50171. this._projectionTextureViewLightDirty = true;
  50172. };
  50173. /**
  50174. * Overrides the position setter to recompute the projection texture view light Matrix.
  50175. */
  50176. SpotLight.prototype._setPosition = function (value) {
  50177. _super.prototype._setPosition.call(this, value);
  50178. this._projectionTextureViewLightDirty = true;
  50179. };
  50180. /**
  50181. * 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.
  50182. * Returns the SpotLight.
  50183. */
  50184. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50185. var activeCamera = this.getScene().activeCamera;
  50186. if (!activeCamera) {
  50187. return;
  50188. }
  50189. this._shadowAngleScale = this._shadowAngleScale || 1;
  50190. var angle = this._shadowAngleScale * this._angle;
  50191. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50192. };
  50193. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50194. this._projectionTextureViewLightDirty = false;
  50195. this._projectionTextureDirty = true;
  50196. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50197. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50198. };
  50199. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50200. this._projectionTextureProjectionLightDirty = false;
  50201. this._projectionTextureDirty = true;
  50202. var light_far = this.projectionTextureLightFar;
  50203. var light_near = this.projectionTextureLightNear;
  50204. var P = light_far / (light_far - light_near);
  50205. var Q = -P * light_near;
  50206. var S = 1.0 / Math.tan(this._angle / 2.0);
  50207. var A = 1.0;
  50208. 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);
  50209. };
  50210. /**
  50211. * Main function for light texture projection matrix computing.
  50212. */
  50213. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50214. this._projectionTextureDirty = false;
  50215. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50216. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50217. };
  50218. SpotLight.prototype._buildUniformLayout = function () {
  50219. this._uniformBuffer.addUniform("vLightData", 4);
  50220. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50221. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50222. this._uniformBuffer.addUniform("vLightDirection", 3);
  50223. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50224. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50225. this._uniformBuffer.addUniform("depthValues", 2);
  50226. this._uniformBuffer.create();
  50227. };
  50228. SpotLight.prototype._computeAngleValues = function () {
  50229. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50230. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50231. };
  50232. /**
  50233. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50234. * @param effect The effect to update
  50235. * @param lightIndex The index of the light in the effect to update
  50236. * @returns The spot light
  50237. */
  50238. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50239. var normalizeDirection;
  50240. if (this.computeTransformedInformation()) {
  50241. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50242. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50243. }
  50244. else {
  50245. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50246. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50247. }
  50248. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50249. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50250. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50251. if (this._projectionTextureViewLightDirty) {
  50252. this._computeProjectionTextureViewLightMatrix();
  50253. }
  50254. if (this._projectionTextureProjectionLightDirty) {
  50255. this._computeProjectionTextureProjectionLightMatrix();
  50256. }
  50257. if (this._projectionTextureDirty) {
  50258. this._computeProjectionTextureMatrix();
  50259. }
  50260. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50261. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50262. }
  50263. return this;
  50264. };
  50265. /**
  50266. * Disposes the light and the associated resources.
  50267. */
  50268. SpotLight.prototype.dispose = function () {
  50269. _super.prototype.dispose.call(this);
  50270. if (this._projectionTexture) {
  50271. this._projectionTexture.dispose();
  50272. }
  50273. };
  50274. /**
  50275. * Prepares the list of defines specific to the light type.
  50276. * @param defines the list of defines
  50277. * @param lightIndex defines the index of the light for the effect
  50278. */
  50279. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50280. defines["SPOTLIGHT" + lightIndex] = true;
  50281. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50282. };
  50283. __decorate([
  50284. BABYLON.serialize()
  50285. ], SpotLight.prototype, "angle", null);
  50286. __decorate([
  50287. BABYLON.serialize()
  50288. ], SpotLight.prototype, "innerAngle", null);
  50289. __decorate([
  50290. BABYLON.serialize()
  50291. ], SpotLight.prototype, "shadowAngleScale", null);
  50292. __decorate([
  50293. BABYLON.serialize()
  50294. ], SpotLight.prototype, "exponent", void 0);
  50295. __decorate([
  50296. BABYLON.serialize()
  50297. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50298. __decorate([
  50299. BABYLON.serialize()
  50300. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50301. __decorate([
  50302. BABYLON.serialize()
  50303. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50304. __decorate([
  50305. BABYLON.serializeAsTexture("projectedLightTexture")
  50306. ], SpotLight.prototype, "_projectionTexture", void 0);
  50307. return SpotLight;
  50308. }(BABYLON.ShadowLight));
  50309. BABYLON.SpotLight = SpotLight;
  50310. })(BABYLON || (BABYLON = {}));
  50311. //# sourceMappingURL=babylon.spotLight.js.map
  50312. var BABYLON;
  50313. (function (BABYLON) {
  50314. /**
  50315. * Class used to override all child animations of a given target
  50316. */
  50317. var AnimationPropertiesOverride = /** @class */ (function () {
  50318. function AnimationPropertiesOverride() {
  50319. /**
  50320. * Gets or sets a value indicating if animation blending must be used
  50321. */
  50322. this.enableBlending = false;
  50323. /**
  50324. * Gets or sets the blending speed to use when enableBlending is true
  50325. */
  50326. this.blendingSpeed = 0.01;
  50327. /**
  50328. * Gets or sets the default loop mode to use
  50329. */
  50330. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50331. }
  50332. return AnimationPropertiesOverride;
  50333. }());
  50334. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50335. })(BABYLON || (BABYLON = {}));
  50336. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50337. var BABYLON;
  50338. (function (BABYLON) {
  50339. /**
  50340. * Represents the range of an animation
  50341. */
  50342. var AnimationRange = /** @class */ (function () {
  50343. /**
  50344. * Initializes the range of an animation
  50345. * @param name The name of the animation range
  50346. * @param from The starting frame of the animation
  50347. * @param to The ending frame of the animation
  50348. */
  50349. function AnimationRange(
  50350. /**The name of the animation range**/
  50351. name,
  50352. /**The starting frame of the animation */
  50353. from,
  50354. /**The ending frame of the animation*/
  50355. to) {
  50356. this.name = name;
  50357. this.from = from;
  50358. this.to = to;
  50359. }
  50360. /**
  50361. * Makes a copy of the animation range
  50362. * @returns A copy of the animation range
  50363. */
  50364. AnimationRange.prototype.clone = function () {
  50365. return new AnimationRange(this.name, this.from, this.to);
  50366. };
  50367. return AnimationRange;
  50368. }());
  50369. BABYLON.AnimationRange = AnimationRange;
  50370. /**
  50371. * Composed of a frame, and an action function
  50372. */
  50373. var AnimationEvent = /** @class */ (function () {
  50374. /**
  50375. * Initializes the animation event
  50376. * @param frame The frame for which the event is triggered
  50377. * @param action The event to perform when triggered
  50378. * @param onlyOnce Specifies if the event should be triggered only once
  50379. */
  50380. function AnimationEvent(
  50381. /** The frame for which the event is triggered **/
  50382. frame,
  50383. /** The event to perform when triggered **/
  50384. action,
  50385. /** Specifies if the event should be triggered only once**/
  50386. onlyOnce) {
  50387. this.frame = frame;
  50388. this.action = action;
  50389. this.onlyOnce = onlyOnce;
  50390. /**
  50391. * Specifies if the animation event is done
  50392. */
  50393. this.isDone = false;
  50394. }
  50395. /** @hidden */
  50396. AnimationEvent.prototype._clone = function () {
  50397. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50398. };
  50399. return AnimationEvent;
  50400. }());
  50401. BABYLON.AnimationEvent = AnimationEvent;
  50402. /**
  50403. * A cursor which tracks a point on a path
  50404. */
  50405. var PathCursor = /** @class */ (function () {
  50406. /**
  50407. * Initializes the path cursor
  50408. * @param path The path to track
  50409. */
  50410. function PathCursor(path) {
  50411. this.path = path;
  50412. /**
  50413. * Stores path cursor callbacks for when an onchange event is triggered
  50414. */
  50415. this._onchange = new Array();
  50416. /**
  50417. * The value of the path cursor
  50418. */
  50419. this.value = 0;
  50420. /**
  50421. * The animation array of the path cursor
  50422. */
  50423. this.animations = new Array();
  50424. }
  50425. /**
  50426. * Gets the cursor point on the path
  50427. * @returns A point on the path cursor at the cursor location
  50428. */
  50429. PathCursor.prototype.getPoint = function () {
  50430. var point = this.path.getPointAtLengthPosition(this.value);
  50431. return new BABYLON.Vector3(point.x, 0, point.y);
  50432. };
  50433. /**
  50434. * Moves the cursor ahead by the step amount
  50435. * @param step The amount to move the cursor forward
  50436. * @returns This path cursor
  50437. */
  50438. PathCursor.prototype.moveAhead = function (step) {
  50439. if (step === void 0) { step = 0.002; }
  50440. this.move(step);
  50441. return this;
  50442. };
  50443. /**
  50444. * Moves the cursor behind by the step amount
  50445. * @param step The amount to move the cursor back
  50446. * @returns This path cursor
  50447. */
  50448. PathCursor.prototype.moveBack = function (step) {
  50449. if (step === void 0) { step = 0.002; }
  50450. this.move(-step);
  50451. return this;
  50452. };
  50453. /**
  50454. * Moves the cursor by the step amount
  50455. * If the step amount is greater than one, an exception is thrown
  50456. * @param step The amount to move the cursor
  50457. * @returns This path cursor
  50458. */
  50459. PathCursor.prototype.move = function (step) {
  50460. if (Math.abs(step) > 1) {
  50461. throw "step size should be less than 1.";
  50462. }
  50463. this.value += step;
  50464. this.ensureLimits();
  50465. this.raiseOnChange();
  50466. return this;
  50467. };
  50468. /**
  50469. * Ensures that the value is limited between zero and one
  50470. * @returns This path cursor
  50471. */
  50472. PathCursor.prototype.ensureLimits = function () {
  50473. while (this.value > 1) {
  50474. this.value -= 1;
  50475. }
  50476. while (this.value < 0) {
  50477. this.value += 1;
  50478. }
  50479. return this;
  50480. };
  50481. /**
  50482. * Runs onchange callbacks on change (used by the animation engine)
  50483. * @returns This path cursor
  50484. */
  50485. PathCursor.prototype.raiseOnChange = function () {
  50486. var _this = this;
  50487. this._onchange.forEach(function (f) { return f(_this); });
  50488. return this;
  50489. };
  50490. /**
  50491. * Executes a function on change
  50492. * @param f A path cursor onchange callback
  50493. * @returns This path cursor
  50494. */
  50495. PathCursor.prototype.onchange = function (f) {
  50496. this._onchange.push(f);
  50497. return this;
  50498. };
  50499. return PathCursor;
  50500. }());
  50501. BABYLON.PathCursor = PathCursor;
  50502. /**
  50503. * Enum for the animation key frame interpolation type
  50504. */
  50505. var AnimationKeyInterpolation;
  50506. (function (AnimationKeyInterpolation) {
  50507. /**
  50508. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50509. */
  50510. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50511. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50512. /**
  50513. * Class used to store any kind of animation
  50514. */
  50515. var Animation = /** @class */ (function () {
  50516. /**
  50517. * Initializes the animation
  50518. * @param name Name of the animation
  50519. * @param targetProperty Property to animate
  50520. * @param framePerSecond The frames per second of the animation
  50521. * @param dataType The data type of the animation
  50522. * @param loopMode The loop mode of the animation
  50523. * @param enableBlendings Specifies if blending should be enabled
  50524. */
  50525. function Animation(
  50526. /**Name of the animation */
  50527. name,
  50528. /**Property to animate */
  50529. targetProperty,
  50530. /**The frames per second of the animation */
  50531. framePerSecond,
  50532. /**The data type of the animation */
  50533. dataType,
  50534. /**The loop mode of the animation */
  50535. loopMode,
  50536. /**Specifies if blending should be enabled */
  50537. enableBlending) {
  50538. this.name = name;
  50539. this.targetProperty = targetProperty;
  50540. this.framePerSecond = framePerSecond;
  50541. this.dataType = dataType;
  50542. this.loopMode = loopMode;
  50543. this.enableBlending = enableBlending;
  50544. /**
  50545. * @hidden Internal use only
  50546. */
  50547. this._runtimeAnimations = new Array();
  50548. /**
  50549. * The set of event that will be linked to this animation
  50550. */
  50551. this._events = new Array();
  50552. /**
  50553. * Stores the blending speed of the animation
  50554. */
  50555. this.blendingSpeed = 0.01;
  50556. /**
  50557. * Stores the animation ranges for the animation
  50558. */
  50559. this._ranges = {};
  50560. this.targetPropertyPath = targetProperty.split(".");
  50561. this.dataType = dataType;
  50562. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50563. }
  50564. /**
  50565. * @hidden Internal use
  50566. */
  50567. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50568. var dataType = undefined;
  50569. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50570. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50571. }
  50572. else if (from instanceof BABYLON.Quaternion) {
  50573. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50574. }
  50575. else if (from instanceof BABYLON.Vector3) {
  50576. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50577. }
  50578. else if (from instanceof BABYLON.Vector2) {
  50579. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50580. }
  50581. else if (from instanceof BABYLON.Color3) {
  50582. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50583. }
  50584. else if (from instanceof BABYLON.Size) {
  50585. dataType = Animation.ANIMATIONTYPE_SIZE;
  50586. }
  50587. if (dataType == undefined) {
  50588. return null;
  50589. }
  50590. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50591. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50592. animation.setKeys(keys);
  50593. if (easingFunction !== undefined) {
  50594. animation.setEasingFunction(easingFunction);
  50595. }
  50596. return animation;
  50597. };
  50598. /**
  50599. * Sets up an animation
  50600. * @param property The property to animate
  50601. * @param animationType The animation type to apply
  50602. * @param framePerSecond The frames per second of the animation
  50603. * @param easingFunction The easing function used in the animation
  50604. * @returns The created animation
  50605. */
  50606. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50607. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50608. animation.setEasingFunction(easingFunction);
  50609. return animation;
  50610. };
  50611. /**
  50612. * Create and start an animation on a node
  50613. * @param name defines the name of the global animation that will be run on all nodes
  50614. * @param node defines the root node where the animation will take place
  50615. * @param targetProperty defines property to animate
  50616. * @param framePerSecond defines the number of frame per second yo use
  50617. * @param totalFrame defines the number of frames in total
  50618. * @param from defines the initial value
  50619. * @param to defines the final value
  50620. * @param loopMode defines which loop mode you want to use (off by default)
  50621. * @param easingFunction defines the easing function to use (linear by default)
  50622. * @param onAnimationEnd defines the callback to call when animation end
  50623. * @returns the animatable created for this animation
  50624. */
  50625. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50626. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50627. if (!animation) {
  50628. return null;
  50629. }
  50630. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50631. };
  50632. /**
  50633. * Create and start an animation on a node and its descendants
  50634. * @param name defines the name of the global animation that will be run on all nodes
  50635. * @param node defines the root node where the animation will take place
  50636. * @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
  50637. * @param targetProperty defines property to animate
  50638. * @param framePerSecond defines the number of frame per second to use
  50639. * @param totalFrame defines the number of frames in total
  50640. * @param from defines the initial value
  50641. * @param to defines the final value
  50642. * @param loopMode defines which loop mode you want to use (off by default)
  50643. * @param easingFunction defines the easing function to use (linear by default)
  50644. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50645. * @returns the list of animatables created for all nodes
  50646. * @example https://www.babylonjs-playground.com/#MH0VLI
  50647. */
  50648. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50649. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50650. if (!animation) {
  50651. return null;
  50652. }
  50653. var scene = node.getScene();
  50654. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50655. };
  50656. /**
  50657. * Creates a new animation, merges it with the existing animations and starts it
  50658. * @param name Name of the animation
  50659. * @param node Node which contains the scene that begins the animations
  50660. * @param targetProperty Specifies which property to animate
  50661. * @param framePerSecond The frames per second of the animation
  50662. * @param totalFrame The total number of frames
  50663. * @param from The frame at the beginning of the animation
  50664. * @param to The frame at the end of the animation
  50665. * @param loopMode Specifies the loop mode of the animation
  50666. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50667. * @param onAnimationEnd Callback to run once the animation is complete
  50668. * @returns Nullable animation
  50669. */
  50670. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50671. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50672. if (!animation) {
  50673. return null;
  50674. }
  50675. node.animations.push(animation);
  50676. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50677. };
  50678. /**
  50679. * Transition property of an host to the target Value
  50680. * @param property The property to transition
  50681. * @param targetValue The target Value of the property
  50682. * @param host The object where the property to animate belongs
  50683. * @param scene Scene used to run the animation
  50684. * @param frameRate Framerate (in frame/s) to use
  50685. * @param transition The transition type we want to use
  50686. * @param duration The duration of the animation, in milliseconds
  50687. * @param onAnimationEnd Callback trigger at the end of the animation
  50688. * @returns Nullable animation
  50689. */
  50690. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50691. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50692. if (duration <= 0) {
  50693. host[property] = targetValue;
  50694. if (onAnimationEnd) {
  50695. onAnimationEnd();
  50696. }
  50697. return null;
  50698. }
  50699. var endFrame = frameRate * (duration / 1000);
  50700. transition.setKeys([{
  50701. frame: 0,
  50702. value: host[property].clone ? host[property].clone() : host[property]
  50703. },
  50704. {
  50705. frame: endFrame,
  50706. value: targetValue
  50707. }]);
  50708. if (!host.animations) {
  50709. host.animations = [];
  50710. }
  50711. host.animations.push(transition);
  50712. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50713. animation.onAnimationEnd = onAnimationEnd;
  50714. return animation;
  50715. };
  50716. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50717. /**
  50718. * Return the array of runtime animations currently using this animation
  50719. */
  50720. get: function () {
  50721. return this._runtimeAnimations;
  50722. },
  50723. enumerable: true,
  50724. configurable: true
  50725. });
  50726. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50727. /**
  50728. * Specifies if any of the runtime animations are currently running
  50729. */
  50730. get: function () {
  50731. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50732. var runtimeAnimation = _a[_i];
  50733. if (!runtimeAnimation.isStopped) {
  50734. return true;
  50735. }
  50736. }
  50737. return false;
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. // Methods
  50743. /**
  50744. * Converts the animation to a string
  50745. * @param fullDetails support for multiple levels of logging within scene loading
  50746. * @returns String form of the animation
  50747. */
  50748. Animation.prototype.toString = function (fullDetails) {
  50749. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50750. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50751. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50752. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50753. if (fullDetails) {
  50754. ret += ", Ranges: {";
  50755. var first = true;
  50756. for (var name in this._ranges) {
  50757. if (first) {
  50758. ret += ", ";
  50759. first = false;
  50760. }
  50761. ret += name;
  50762. }
  50763. ret += "}";
  50764. }
  50765. return ret;
  50766. };
  50767. /**
  50768. * Add an event to this animation
  50769. * @param event Event to add
  50770. */
  50771. Animation.prototype.addEvent = function (event) {
  50772. this._events.push(event);
  50773. };
  50774. /**
  50775. * Remove all events found at the given frame
  50776. * @param frame The frame to remove events from
  50777. */
  50778. Animation.prototype.removeEvents = function (frame) {
  50779. for (var index = 0; index < this._events.length; index++) {
  50780. if (this._events[index].frame === frame) {
  50781. this._events.splice(index, 1);
  50782. index--;
  50783. }
  50784. }
  50785. };
  50786. /**
  50787. * Retrieves all the events from the animation
  50788. * @returns Events from the animation
  50789. */
  50790. Animation.prototype.getEvents = function () {
  50791. return this._events;
  50792. };
  50793. /**
  50794. * Creates an animation range
  50795. * @param name Name of the animation range
  50796. * @param from Starting frame of the animation range
  50797. * @param to Ending frame of the animation
  50798. */
  50799. Animation.prototype.createRange = function (name, from, to) {
  50800. // check name not already in use; could happen for bones after serialized
  50801. if (!this._ranges[name]) {
  50802. this._ranges[name] = new AnimationRange(name, from, to);
  50803. }
  50804. };
  50805. /**
  50806. * Deletes an animation range by name
  50807. * @param name Name of the animation range to delete
  50808. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50809. */
  50810. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50811. if (deleteFrames === void 0) { deleteFrames = true; }
  50812. var range = this._ranges[name];
  50813. if (!range) {
  50814. return;
  50815. }
  50816. if (deleteFrames) {
  50817. var from = range.from;
  50818. var to = range.to;
  50819. // this loop MUST go high to low for multiple splices to work
  50820. for (var key = this._keys.length - 1; key >= 0; key--) {
  50821. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50822. this._keys.splice(key, 1);
  50823. }
  50824. }
  50825. }
  50826. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50827. };
  50828. /**
  50829. * Gets the animation range by name, or null if not defined
  50830. * @param name Name of the animation range
  50831. * @returns Nullable animation range
  50832. */
  50833. Animation.prototype.getRange = function (name) {
  50834. return this._ranges[name];
  50835. };
  50836. /**
  50837. * Gets the key frames from the animation
  50838. * @returns The key frames of the animation
  50839. */
  50840. Animation.prototype.getKeys = function () {
  50841. return this._keys;
  50842. };
  50843. /**
  50844. * Gets the highest frame rate of the animation
  50845. * @returns Highest frame rate of the animation
  50846. */
  50847. Animation.prototype.getHighestFrame = function () {
  50848. var ret = 0;
  50849. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50850. if (ret < this._keys[key].frame) {
  50851. ret = this._keys[key].frame;
  50852. }
  50853. }
  50854. return ret;
  50855. };
  50856. /**
  50857. * Gets the easing function of the animation
  50858. * @returns Easing function of the animation
  50859. */
  50860. Animation.prototype.getEasingFunction = function () {
  50861. return this._easingFunction;
  50862. };
  50863. /**
  50864. * Sets the easing function of the animation
  50865. * @param easingFunction A custom mathematical formula for animation
  50866. */
  50867. Animation.prototype.setEasingFunction = function (easingFunction) {
  50868. this._easingFunction = easingFunction;
  50869. };
  50870. /**
  50871. * Interpolates a scalar linearly
  50872. * @param startValue Start value of the animation curve
  50873. * @param endValue End value of the animation curve
  50874. * @param gradient Scalar amount to interpolate
  50875. * @returns Interpolated scalar value
  50876. */
  50877. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50878. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50879. };
  50880. /**
  50881. * Interpolates a scalar cubically
  50882. * @param startValue Start value of the animation curve
  50883. * @param outTangent End tangent of the animation
  50884. * @param endValue End value of the animation curve
  50885. * @param inTangent Start tangent of the animation curve
  50886. * @param gradient Scalar amount to interpolate
  50887. * @returns Interpolated scalar value
  50888. */
  50889. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50890. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50891. };
  50892. /**
  50893. * Interpolates a quaternion using a spherical linear interpolation
  50894. * @param startValue Start value of the animation curve
  50895. * @param endValue End value of the animation curve
  50896. * @param gradient Scalar amount to interpolate
  50897. * @returns Interpolated quaternion value
  50898. */
  50899. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50900. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50901. };
  50902. /**
  50903. * Interpolates a quaternion cubically
  50904. * @param startValue Start value of the animation curve
  50905. * @param outTangent End tangent of the animation curve
  50906. * @param endValue End value of the animation curve
  50907. * @param inTangent Start tangent of the animation curve
  50908. * @param gradient Scalar amount to interpolate
  50909. * @returns Interpolated quaternion value
  50910. */
  50911. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50912. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50913. };
  50914. /**
  50915. * Interpolates a Vector3 linearl
  50916. * @param startValue Start value of the animation curve
  50917. * @param endValue End value of the animation curve
  50918. * @param gradient Scalar amount to interpolate
  50919. * @returns Interpolated scalar value
  50920. */
  50921. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50922. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50923. };
  50924. /**
  50925. * Interpolates a Vector3 cubically
  50926. * @param startValue Start value of the animation curve
  50927. * @param outTangent End tangent of the animation
  50928. * @param endValue End value of the animation curve
  50929. * @param inTangent Start tangent of the animation curve
  50930. * @param gradient Scalar amount to interpolate
  50931. * @returns InterpolatedVector3 value
  50932. */
  50933. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50934. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50935. };
  50936. /**
  50937. * Interpolates a Vector2 linearly
  50938. * @param startValue Start value of the animation curve
  50939. * @param endValue End value of the animation curve
  50940. * @param gradient Scalar amount to interpolate
  50941. * @returns Interpolated Vector2 value
  50942. */
  50943. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50944. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50945. };
  50946. /**
  50947. * Interpolates a Vector2 cubically
  50948. * @param startValue Start value of the animation curve
  50949. * @param outTangent End tangent of the animation
  50950. * @param endValue End value of the animation curve
  50951. * @param inTangent Start tangent of the animation curve
  50952. * @param gradient Scalar amount to interpolate
  50953. * @returns Interpolated Vector2 value
  50954. */
  50955. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50956. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50957. };
  50958. /**
  50959. * Interpolates a size linearly
  50960. * @param startValue Start value of the animation curve
  50961. * @param endValue End value of the animation curve
  50962. * @param gradient Scalar amount to interpolate
  50963. * @returns Interpolated Size value
  50964. */
  50965. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50966. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50967. };
  50968. /**
  50969. * Interpolates a Color3 linearly
  50970. * @param startValue Start value of the animation curve
  50971. * @param endValue End value of the animation curve
  50972. * @param gradient Scalar amount to interpolate
  50973. * @returns Interpolated Color3 value
  50974. */
  50975. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50976. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50977. };
  50978. /**
  50979. * @hidden Internal use only
  50980. */
  50981. Animation.prototype._getKeyValue = function (value) {
  50982. if (typeof value === "function") {
  50983. return value();
  50984. }
  50985. return value;
  50986. };
  50987. /**
  50988. * @hidden Internal use only
  50989. */
  50990. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50991. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50992. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50993. }
  50994. var keys = this.getKeys();
  50995. // Try to get a hash to find the right key
  50996. 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));
  50997. if (keys[startKeyIndex].frame >= currentFrame) {
  50998. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50999. startKeyIndex--;
  51000. }
  51001. }
  51002. for (var key = startKeyIndex; key < keys.length; key++) {
  51003. var endKey = keys[key + 1];
  51004. if (endKey.frame >= currentFrame) {
  51005. var startKey = keys[key];
  51006. var startValue = this._getKeyValue(startKey.value);
  51007. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51008. return startValue;
  51009. }
  51010. var endValue = this._getKeyValue(endKey.value);
  51011. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51012. var frameDelta = endKey.frame - startKey.frame;
  51013. // gradient : percent of currentFrame between the frame inf and the frame sup
  51014. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51015. // check for easingFunction and correction of gradient
  51016. var easingFunction = this.getEasingFunction();
  51017. if (easingFunction != null) {
  51018. gradient = easingFunction.ease(gradient);
  51019. }
  51020. switch (this.dataType) {
  51021. // Float
  51022. case Animation.ANIMATIONTYPE_FLOAT:
  51023. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51024. switch (loopMode) {
  51025. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51026. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51027. return floatValue;
  51028. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51029. return offsetValue * repeatCount + floatValue;
  51030. }
  51031. break;
  51032. // Quaternion
  51033. case Animation.ANIMATIONTYPE_QUATERNION:
  51034. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51035. switch (loopMode) {
  51036. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51037. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51038. return quatValue;
  51039. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51040. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51041. }
  51042. return quatValue;
  51043. // Vector3
  51044. case Animation.ANIMATIONTYPE_VECTOR3:
  51045. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51046. switch (loopMode) {
  51047. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51048. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51049. return vec3Value;
  51050. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51051. return vec3Value.add(offsetValue.scale(repeatCount));
  51052. }
  51053. // Vector2
  51054. case Animation.ANIMATIONTYPE_VECTOR2:
  51055. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51056. switch (loopMode) {
  51057. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51058. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51059. return vec2Value;
  51060. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51061. return vec2Value.add(offsetValue.scale(repeatCount));
  51062. }
  51063. // Size
  51064. case Animation.ANIMATIONTYPE_SIZE:
  51065. switch (loopMode) {
  51066. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51067. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51068. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51069. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51070. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51071. }
  51072. // Color3
  51073. case Animation.ANIMATIONTYPE_COLOR3:
  51074. switch (loopMode) {
  51075. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51076. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51077. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51078. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51079. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51080. }
  51081. // Matrix
  51082. case Animation.ANIMATIONTYPE_MATRIX:
  51083. switch (loopMode) {
  51084. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51085. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51086. if (Animation.AllowMatricesInterpolation) {
  51087. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51088. }
  51089. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51090. return startValue;
  51091. }
  51092. default:
  51093. break;
  51094. }
  51095. break;
  51096. }
  51097. }
  51098. return this._getKeyValue(keys[keys.length - 1].value);
  51099. };
  51100. /**
  51101. * Defines the function to use to interpolate matrices
  51102. * @param startValue defines the start matrix
  51103. * @param endValue defines the end matrix
  51104. * @param gradient defines the gradient between both matrices
  51105. * @param result defines an optional target matrix where to store the interpolation
  51106. * @returns the interpolated matrix
  51107. */
  51108. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51109. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51110. if (result) {
  51111. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51112. return result;
  51113. }
  51114. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51115. }
  51116. if (result) {
  51117. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51118. return result;
  51119. }
  51120. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51121. };
  51122. /**
  51123. * Makes a copy of the animation
  51124. * @returns Cloned animation
  51125. */
  51126. Animation.prototype.clone = function () {
  51127. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51128. clone.enableBlending = this.enableBlending;
  51129. clone.blendingSpeed = this.blendingSpeed;
  51130. if (this._keys) {
  51131. clone.setKeys(this._keys);
  51132. }
  51133. if (this._ranges) {
  51134. clone._ranges = {};
  51135. for (var name in this._ranges) {
  51136. var range = this._ranges[name];
  51137. if (!range) {
  51138. continue;
  51139. }
  51140. clone._ranges[name] = range.clone();
  51141. }
  51142. }
  51143. return clone;
  51144. };
  51145. /**
  51146. * Sets the key frames of the animation
  51147. * @param values The animation key frames to set
  51148. */
  51149. Animation.prototype.setKeys = function (values) {
  51150. this._keys = values.slice(0);
  51151. };
  51152. /**
  51153. * Serializes the animation to an object
  51154. * @returns Serialized object
  51155. */
  51156. Animation.prototype.serialize = function () {
  51157. var serializationObject = {};
  51158. serializationObject.name = this.name;
  51159. serializationObject.property = this.targetProperty;
  51160. serializationObject.framePerSecond = this.framePerSecond;
  51161. serializationObject.dataType = this.dataType;
  51162. serializationObject.loopBehavior = this.loopMode;
  51163. serializationObject.enableBlending = this.enableBlending;
  51164. serializationObject.blendingSpeed = this.blendingSpeed;
  51165. var dataType = this.dataType;
  51166. serializationObject.keys = [];
  51167. var keys = this.getKeys();
  51168. for (var index = 0; index < keys.length; index++) {
  51169. var animationKey = keys[index];
  51170. var key = {};
  51171. key.frame = animationKey.frame;
  51172. switch (dataType) {
  51173. case Animation.ANIMATIONTYPE_FLOAT:
  51174. key.values = [animationKey.value];
  51175. break;
  51176. case Animation.ANIMATIONTYPE_QUATERNION:
  51177. case Animation.ANIMATIONTYPE_MATRIX:
  51178. case Animation.ANIMATIONTYPE_VECTOR3:
  51179. case Animation.ANIMATIONTYPE_COLOR3:
  51180. key.values = animationKey.value.asArray();
  51181. break;
  51182. }
  51183. serializationObject.keys.push(key);
  51184. }
  51185. serializationObject.ranges = [];
  51186. for (var name in this._ranges) {
  51187. var source = this._ranges[name];
  51188. if (!source) {
  51189. continue;
  51190. }
  51191. var range = {};
  51192. range.name = name;
  51193. range.from = source.from;
  51194. range.to = source.to;
  51195. serializationObject.ranges.push(range);
  51196. }
  51197. return serializationObject;
  51198. };
  51199. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51200. /**
  51201. * Get the float animation type
  51202. */
  51203. get: function () {
  51204. return Animation._ANIMATIONTYPE_FLOAT;
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51210. /**
  51211. * Get the Vector3 animation type
  51212. */
  51213. get: function () {
  51214. return Animation._ANIMATIONTYPE_VECTOR3;
  51215. },
  51216. enumerable: true,
  51217. configurable: true
  51218. });
  51219. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51220. /**
  51221. * Get the Vector2 animation type
  51222. */
  51223. get: function () {
  51224. return Animation._ANIMATIONTYPE_VECTOR2;
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51230. /**
  51231. * Get the Size animation type
  51232. */
  51233. get: function () {
  51234. return Animation._ANIMATIONTYPE_SIZE;
  51235. },
  51236. enumerable: true,
  51237. configurable: true
  51238. });
  51239. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51240. /**
  51241. * Get the Quaternion animation type
  51242. */
  51243. get: function () {
  51244. return Animation._ANIMATIONTYPE_QUATERNION;
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51250. /**
  51251. * Get the Matrix animation type
  51252. */
  51253. get: function () {
  51254. return Animation._ANIMATIONTYPE_MATRIX;
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51260. /**
  51261. * Get the Color3 animation type
  51262. */
  51263. get: function () {
  51264. return Animation._ANIMATIONTYPE_COLOR3;
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51270. /**
  51271. * Get the Relative Loop Mode
  51272. */
  51273. get: function () {
  51274. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51280. /**
  51281. * Get the Cycle Loop Mode
  51282. */
  51283. get: function () {
  51284. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51285. },
  51286. enumerable: true,
  51287. configurable: true
  51288. });
  51289. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51290. /**
  51291. * Get the Constant Loop Mode
  51292. */
  51293. get: function () {
  51294. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51295. },
  51296. enumerable: true,
  51297. configurable: true
  51298. });
  51299. /** @hidden */
  51300. Animation._UniversalLerp = function (left, right, amount) {
  51301. var constructor = left.constructor;
  51302. if (constructor.Lerp) { // Lerp supported
  51303. return constructor.Lerp(left, right, amount);
  51304. }
  51305. else if (constructor.Slerp) { // Slerp supported
  51306. return constructor.Slerp(left, right, amount);
  51307. }
  51308. else if (left.toFixed) { // Number
  51309. return left * (1.0 - amount) + amount * right;
  51310. }
  51311. else { // Blending not supported
  51312. return right;
  51313. }
  51314. };
  51315. /**
  51316. * Parses an animation object and creates an animation
  51317. * @param parsedAnimation Parsed animation object
  51318. * @returns Animation object
  51319. */
  51320. Animation.Parse = function (parsedAnimation) {
  51321. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51322. var dataType = parsedAnimation.dataType;
  51323. var keys = [];
  51324. var data;
  51325. var index;
  51326. if (parsedAnimation.enableBlending) {
  51327. animation.enableBlending = parsedAnimation.enableBlending;
  51328. }
  51329. if (parsedAnimation.blendingSpeed) {
  51330. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51331. }
  51332. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51333. var key = parsedAnimation.keys[index];
  51334. var inTangent;
  51335. var outTangent;
  51336. switch (dataType) {
  51337. case Animation.ANIMATIONTYPE_FLOAT:
  51338. data = key.values[0];
  51339. if (key.values.length >= 1) {
  51340. inTangent = key.values[1];
  51341. }
  51342. if (key.values.length >= 2) {
  51343. outTangent = key.values[2];
  51344. }
  51345. break;
  51346. case Animation.ANIMATIONTYPE_QUATERNION:
  51347. data = BABYLON.Quaternion.FromArray(key.values);
  51348. if (key.values.length >= 8) {
  51349. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51350. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51351. inTangent = _inTangent;
  51352. }
  51353. }
  51354. if (key.values.length >= 12) {
  51355. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51356. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51357. outTangent = _outTangent;
  51358. }
  51359. }
  51360. break;
  51361. case Animation.ANIMATIONTYPE_MATRIX:
  51362. data = BABYLON.Matrix.FromArray(key.values);
  51363. break;
  51364. case Animation.ANIMATIONTYPE_COLOR3:
  51365. data = BABYLON.Color3.FromArray(key.values);
  51366. break;
  51367. case Animation.ANIMATIONTYPE_VECTOR3:
  51368. default:
  51369. data = BABYLON.Vector3.FromArray(key.values);
  51370. break;
  51371. }
  51372. var keyData = {};
  51373. keyData.frame = key.frame;
  51374. keyData.value = data;
  51375. if (inTangent != undefined) {
  51376. keyData.inTangent = inTangent;
  51377. }
  51378. if (outTangent != undefined) {
  51379. keyData.outTangent = outTangent;
  51380. }
  51381. keys.push(keyData);
  51382. }
  51383. animation.setKeys(keys);
  51384. if (parsedAnimation.ranges) {
  51385. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51386. data = parsedAnimation.ranges[index];
  51387. animation.createRange(data.name, data.from, data.to);
  51388. }
  51389. }
  51390. return animation;
  51391. };
  51392. /**
  51393. * Appends the serialized animations from the source animations
  51394. * @param source Source containing the animations
  51395. * @param destination Target to store the animations
  51396. */
  51397. Animation.AppendSerializedAnimations = function (source, destination) {
  51398. if (source.animations) {
  51399. destination.animations = [];
  51400. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51401. var animation = source.animations[animationIndex];
  51402. destination.animations.push(animation.serialize());
  51403. }
  51404. }
  51405. };
  51406. /**
  51407. * Use matrix interpolation instead of using direct key value when animating matrices
  51408. */
  51409. Animation.AllowMatricesInterpolation = false;
  51410. /**
  51411. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51412. */
  51413. Animation.AllowMatrixDecomposeForInterpolation = true;
  51414. // Statics
  51415. /**
  51416. * Float animation type
  51417. */
  51418. Animation._ANIMATIONTYPE_FLOAT = 0;
  51419. /**
  51420. * Vector3 animation type
  51421. */
  51422. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51423. /**
  51424. * Quaternion animation type
  51425. */
  51426. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51427. /**
  51428. * Matrix animation type
  51429. */
  51430. Animation._ANIMATIONTYPE_MATRIX = 3;
  51431. /**
  51432. * Color3 animation type
  51433. */
  51434. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51435. /**
  51436. * Vector2 animation type
  51437. */
  51438. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51439. /**
  51440. * Size animation type
  51441. */
  51442. Animation._ANIMATIONTYPE_SIZE = 6;
  51443. /**
  51444. * Relative Loop Mode
  51445. */
  51446. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51447. /**
  51448. * Cycle Loop Mode
  51449. */
  51450. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51451. /**
  51452. * Constant Loop Mode
  51453. */
  51454. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51455. return Animation;
  51456. }());
  51457. BABYLON.Animation = Animation;
  51458. })(BABYLON || (BABYLON = {}));
  51459. //# sourceMappingURL=babylon.animation.js.map
  51460. var BABYLON;
  51461. (function (BABYLON) {
  51462. /**
  51463. * This class defines the direct association between an animation and a target
  51464. */
  51465. var TargetedAnimation = /** @class */ (function () {
  51466. function TargetedAnimation() {
  51467. }
  51468. return TargetedAnimation;
  51469. }());
  51470. BABYLON.TargetedAnimation = TargetedAnimation;
  51471. /**
  51472. * Use this class to create coordinated animations on multiple targets
  51473. */
  51474. var AnimationGroup = /** @class */ (function () {
  51475. /**
  51476. * Instantiates a new Animation Group.
  51477. * This helps managing several animations at once.
  51478. * @see http://doc.babylonjs.com/how_to/group
  51479. * @param name Defines the name of the group
  51480. * @param scene Defines the scene the group belongs to
  51481. */
  51482. function AnimationGroup(
  51483. /** The name of the animation group */
  51484. name, scene) {
  51485. if (scene === void 0) { scene = null; }
  51486. this.name = name;
  51487. this._targetedAnimations = new Array();
  51488. this._animatables = new Array();
  51489. this._from = Number.MAX_VALUE;
  51490. this._to = -Number.MAX_VALUE;
  51491. this._speedRatio = 1;
  51492. /**
  51493. * This observable will notify when one animation have ended.
  51494. */
  51495. this.onAnimationEndObservable = new BABYLON.Observable();
  51496. /**
  51497. * This observable will notify when all animations have ended.
  51498. */
  51499. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51500. /**
  51501. * This observable will notify when all animations have paused.
  51502. */
  51503. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51504. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51505. this._scene.animationGroups.push(this);
  51506. }
  51507. Object.defineProperty(AnimationGroup.prototype, "from", {
  51508. /**
  51509. * Gets the first frame
  51510. */
  51511. get: function () {
  51512. return this._from;
  51513. },
  51514. enumerable: true,
  51515. configurable: true
  51516. });
  51517. Object.defineProperty(AnimationGroup.prototype, "to", {
  51518. /**
  51519. * Gets the last frame
  51520. */
  51521. get: function () {
  51522. return this._to;
  51523. },
  51524. enumerable: true,
  51525. configurable: true
  51526. });
  51527. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51528. /**
  51529. * Define if the animations are started
  51530. */
  51531. get: function () {
  51532. return this._isStarted;
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51538. /**
  51539. * Gets or sets the speed ratio to use for all animations
  51540. */
  51541. get: function () {
  51542. return this._speedRatio;
  51543. },
  51544. /**
  51545. * Gets or sets the speed ratio to use for all animations
  51546. */
  51547. set: function (value) {
  51548. if (this._speedRatio === value) {
  51549. return;
  51550. }
  51551. this._speedRatio = value;
  51552. for (var index = 0; index < this._animatables.length; index++) {
  51553. var animatable = this._animatables[index];
  51554. animatable.speedRatio = this._speedRatio;
  51555. }
  51556. },
  51557. enumerable: true,
  51558. configurable: true
  51559. });
  51560. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51561. /**
  51562. * Gets the targeted animations for this animation group
  51563. */
  51564. get: function () {
  51565. return this._targetedAnimations;
  51566. },
  51567. enumerable: true,
  51568. configurable: true
  51569. });
  51570. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51571. /**
  51572. * returning the list of animatables controlled by this animation group.
  51573. */
  51574. get: function () {
  51575. return this._animatables;
  51576. },
  51577. enumerable: true,
  51578. configurable: true
  51579. });
  51580. /**
  51581. * Add an animation (with its target) in the group
  51582. * @param animation defines the animation we want to add
  51583. * @param target defines the target of the animation
  51584. * @returns the {BABYLON.TargetedAnimation} object
  51585. */
  51586. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51587. var targetedAnimation = {
  51588. animation: animation,
  51589. target: target
  51590. };
  51591. var keys = animation.getKeys();
  51592. if (this._from > keys[0].frame) {
  51593. this._from = keys[0].frame;
  51594. }
  51595. if (this._to < keys[keys.length - 1].frame) {
  51596. this._to = keys[keys.length - 1].frame;
  51597. }
  51598. this._targetedAnimations.push(targetedAnimation);
  51599. return targetedAnimation;
  51600. };
  51601. /**
  51602. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51603. * It can add constant keys at begin or end
  51604. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51605. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51606. * @returns the animation group
  51607. */
  51608. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51609. if (beginFrame === void 0) { beginFrame = null; }
  51610. if (endFrame === void 0) { endFrame = null; }
  51611. if (beginFrame == null)
  51612. beginFrame = this._from;
  51613. if (endFrame == null)
  51614. endFrame = this._to;
  51615. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51616. var targetedAnimation = this._targetedAnimations[index];
  51617. var keys = targetedAnimation.animation.getKeys();
  51618. var startKey = keys[0];
  51619. var endKey = keys[keys.length - 1];
  51620. if (startKey.frame > beginFrame) {
  51621. var newKey = {
  51622. frame: beginFrame,
  51623. value: startKey.value,
  51624. inTangent: startKey.inTangent,
  51625. outTangent: startKey.outTangent,
  51626. interpolation: startKey.interpolation
  51627. };
  51628. keys.splice(0, 0, newKey);
  51629. }
  51630. if (endKey.frame < endFrame) {
  51631. var newKey = {
  51632. frame: endFrame,
  51633. value: endKey.value,
  51634. inTangent: endKey.outTangent,
  51635. outTangent: endKey.outTangent,
  51636. interpolation: endKey.interpolation
  51637. };
  51638. keys.push(newKey);
  51639. }
  51640. }
  51641. this._from = beginFrame;
  51642. this._to = endFrame;
  51643. return this;
  51644. };
  51645. /**
  51646. * Start all animations on given targets
  51647. * @param loop defines if animations must loop
  51648. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51649. * @param from defines the from key (optional)
  51650. * @param to defines the to key (optional)
  51651. * @returns the current animation group
  51652. */
  51653. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51654. var _this = this;
  51655. if (loop === void 0) { loop = false; }
  51656. if (speedRatio === void 0) { speedRatio = 1; }
  51657. if (this._isStarted || this._targetedAnimations.length === 0) {
  51658. return this;
  51659. }
  51660. var _loop_1 = function (targetedAnimation) {
  51661. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51662. animatable.onAnimationEnd = function () {
  51663. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51664. _this._checkAnimationGroupEnded(animatable);
  51665. };
  51666. this_1._animatables.push(animatable);
  51667. };
  51668. var this_1 = this;
  51669. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51670. var targetedAnimation = _a[_i];
  51671. _loop_1(targetedAnimation);
  51672. }
  51673. this._speedRatio = speedRatio;
  51674. this._isStarted = true;
  51675. return this;
  51676. };
  51677. /**
  51678. * Pause all animations
  51679. * @returns the animation group
  51680. */
  51681. AnimationGroup.prototype.pause = function () {
  51682. if (!this._isStarted) {
  51683. return this;
  51684. }
  51685. for (var index = 0; index < this._animatables.length; index++) {
  51686. var animatable = this._animatables[index];
  51687. animatable.pause();
  51688. }
  51689. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51690. return this;
  51691. };
  51692. /**
  51693. * Play all animations to initial state
  51694. * This function will start() the animations if they were not started or will restart() them if they were paused
  51695. * @param loop defines if animations must loop
  51696. * @returns the animation group
  51697. */
  51698. AnimationGroup.prototype.play = function (loop) {
  51699. // only if all animatables are ready and exist
  51700. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51701. if (loop !== undefined) {
  51702. for (var index = 0; index < this._animatables.length; index++) {
  51703. var animatable = this._animatables[index];
  51704. animatable.loopAnimation = loop;
  51705. }
  51706. }
  51707. this.restart();
  51708. }
  51709. else {
  51710. this.stop();
  51711. this.start(loop, this._speedRatio);
  51712. }
  51713. return this;
  51714. };
  51715. /**
  51716. * Reset all animations to initial state
  51717. * @returns the animation group
  51718. */
  51719. AnimationGroup.prototype.reset = function () {
  51720. if (!this._isStarted) {
  51721. return this;
  51722. }
  51723. for (var index = 0; index < this._animatables.length; index++) {
  51724. var animatable = this._animatables[index];
  51725. animatable.reset();
  51726. }
  51727. return this;
  51728. };
  51729. /**
  51730. * Restart animations from key 0
  51731. * @returns the animation group
  51732. */
  51733. AnimationGroup.prototype.restart = function () {
  51734. if (!this._isStarted) {
  51735. return this;
  51736. }
  51737. for (var index = 0; index < this._animatables.length; index++) {
  51738. var animatable = this._animatables[index];
  51739. animatable.restart();
  51740. }
  51741. return this;
  51742. };
  51743. /**
  51744. * Stop all animations
  51745. * @returns the animation group
  51746. */
  51747. AnimationGroup.prototype.stop = function () {
  51748. if (!this._isStarted) {
  51749. return this;
  51750. }
  51751. var list = this._animatables.slice();
  51752. for (var index = 0; index < list.length; index++) {
  51753. list[index].stop();
  51754. }
  51755. this._isStarted = false;
  51756. return this;
  51757. };
  51758. /**
  51759. * Set animation weight for all animatables
  51760. * @param weight defines the weight to use
  51761. * @return the animationGroup
  51762. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51763. */
  51764. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51765. for (var index = 0; index < this._animatables.length; index++) {
  51766. var animatable = this._animatables[index];
  51767. animatable.weight = weight;
  51768. }
  51769. return this;
  51770. };
  51771. /**
  51772. * Synchronize and normalize all animatables with a source animatable
  51773. * @param root defines the root animatable to synchronize with
  51774. * @return the animationGroup
  51775. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51776. */
  51777. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51778. for (var index = 0; index < this._animatables.length; index++) {
  51779. var animatable = this._animatables[index];
  51780. animatable.syncWith(root);
  51781. }
  51782. return this;
  51783. };
  51784. /**
  51785. * Goes to a specific frame in this animation group
  51786. * @param frame the frame number to go to
  51787. * @return the animationGroup
  51788. */
  51789. AnimationGroup.prototype.goToFrame = function (frame) {
  51790. if (!this._isStarted) {
  51791. return this;
  51792. }
  51793. for (var index = 0; index < this._animatables.length; index++) {
  51794. var animatable = this._animatables[index];
  51795. animatable.goToFrame(frame);
  51796. }
  51797. return this;
  51798. };
  51799. /**
  51800. * Dispose all associated resources
  51801. */
  51802. AnimationGroup.prototype.dispose = function () {
  51803. this._targetedAnimations = [];
  51804. this._animatables = [];
  51805. var index = this._scene.animationGroups.indexOf(this);
  51806. if (index > -1) {
  51807. this._scene.animationGroups.splice(index, 1);
  51808. }
  51809. };
  51810. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51811. // animatable should be taken out of the array
  51812. var idx = this._animatables.indexOf(animatable);
  51813. if (idx > -1) {
  51814. this._animatables.splice(idx, 1);
  51815. }
  51816. // all animatables were removed? animation group ended!
  51817. if (this._animatables.length === 0) {
  51818. this._isStarted = false;
  51819. this.onAnimationGroupEndObservable.notifyObservers(this);
  51820. }
  51821. };
  51822. // Statics
  51823. /**
  51824. * Returns a new AnimationGroup object parsed from the source provided.
  51825. * @param parsedAnimationGroup defines the source
  51826. * @param scene defines the scene that will receive the animationGroup
  51827. * @returns a new AnimationGroup
  51828. */
  51829. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51830. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51831. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51832. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51833. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51834. var id = targetedAnimation.targetId;
  51835. var targetNode = scene.getNodeByID(id);
  51836. if (targetNode != null)
  51837. animationGroup.addTargetedAnimation(animation, targetNode);
  51838. }
  51839. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51840. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51841. return animationGroup;
  51842. };
  51843. /**
  51844. * Returns the string "AnimationGroup"
  51845. * @returns "AnimationGroup"
  51846. */
  51847. AnimationGroup.prototype.getClassName = function () {
  51848. return "AnimationGroup";
  51849. };
  51850. /**
  51851. * Creates a detailled string about the object
  51852. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51853. * @returns a string representing the object
  51854. */
  51855. AnimationGroup.prototype.toString = function (fullDetails) {
  51856. var ret = "Name: " + this.name;
  51857. ret += ", type: " + this.getClassName();
  51858. if (fullDetails) {
  51859. ret += ", from: " + this._from;
  51860. ret += ", to: " + this._to;
  51861. ret += ", isStarted: " + this._isStarted;
  51862. ret += ", speedRatio: " + this._speedRatio;
  51863. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51864. ret += ", animatables length: " + this._animatables;
  51865. }
  51866. return ret;
  51867. };
  51868. return AnimationGroup;
  51869. }());
  51870. BABYLON.AnimationGroup = AnimationGroup;
  51871. })(BABYLON || (BABYLON = {}));
  51872. //# sourceMappingURL=babylon.animationGroup.js.map
  51873. var BABYLON;
  51874. (function (BABYLON) {
  51875. // Static values to help the garbage collector
  51876. // Quaternion
  51877. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51878. // Vector3
  51879. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51880. // Vector2
  51881. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51882. // Size
  51883. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51884. // Color3
  51885. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51886. /**
  51887. * Defines a runtime animation
  51888. */
  51889. var RuntimeAnimation = /** @class */ (function () {
  51890. /**
  51891. * Create a new RuntimeAnimation object
  51892. * @param target defines the target of the animation
  51893. * @param animation defines the source animation object
  51894. * @param scene defines the hosting scene
  51895. * @param host defines the initiating Animatable
  51896. */
  51897. function RuntimeAnimation(target, animation, scene, host) {
  51898. var _this = this;
  51899. this._events = new Array();
  51900. /**
  51901. * The current frame of the runtime animation
  51902. */
  51903. this._currentFrame = 0;
  51904. /**
  51905. * The original value of the runtime animation
  51906. */
  51907. this._originalValue = new Array();
  51908. /**
  51909. * The offsets cache of the runtime animation
  51910. */
  51911. this._offsetsCache = {};
  51912. /**
  51913. * The high limits cache of the runtime animation
  51914. */
  51915. this._highLimitsCache = {};
  51916. /**
  51917. * Specifies if the runtime animation has been stopped
  51918. */
  51919. this._stopped = false;
  51920. /**
  51921. * The blending factor of the runtime animation
  51922. */
  51923. this._blendingFactor = 0;
  51924. /**
  51925. * The target path of the runtime animation
  51926. */
  51927. this._targetPath = "";
  51928. /**
  51929. * The weight of the runtime animation
  51930. */
  51931. this._weight = 1.0;
  51932. /**
  51933. * The ratio offset of the runtime animation
  51934. */
  51935. this._ratioOffset = 0;
  51936. /**
  51937. * The previous delay of the runtime animation
  51938. */
  51939. this._previousDelay = 0;
  51940. /**
  51941. * The previous ratio of the runtime animation
  51942. */
  51943. this._previousRatio = 0;
  51944. this._animation = animation;
  51945. this._target = target;
  51946. this._scene = scene;
  51947. this._host = host;
  51948. animation._runtimeAnimations.push(this);
  51949. // Cloning events locally
  51950. var events = animation.getEvents();
  51951. if (events && events.length > 0) {
  51952. events.forEach(function (e) {
  51953. _this._events.push(e._clone());
  51954. });
  51955. }
  51956. }
  51957. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51958. /**
  51959. * Gets the current frame of the runtime animation
  51960. */
  51961. get: function () {
  51962. return this._currentFrame;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51968. /**
  51969. * Gets the weight of the runtime animation
  51970. */
  51971. get: function () {
  51972. return this._weight;
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51978. /**
  51979. * Gets the current value of the runtime animation
  51980. */
  51981. get: function () {
  51982. return this._currentValue;
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51988. /**
  51989. * Gets the target path of the runtime animation
  51990. */
  51991. get: function () {
  51992. return this._targetPath;
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51998. /**
  51999. * Gets the actual target of the runtime animation
  52000. */
  52001. get: function () {
  52002. return this._activeTarget;
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52008. /**
  52009. * Gets the animation from the runtime animation
  52010. */
  52011. get: function () {
  52012. return this._animation;
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. /**
  52018. * Resets the runtime animation to the beginning
  52019. * @param restoreOriginal defines whether to restore the target property to the original value
  52020. */
  52021. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52022. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52023. if (restoreOriginal) {
  52024. if (this._target instanceof Array) {
  52025. var index = 0;
  52026. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52027. var target = _a[_i];
  52028. if (this._originalValue[index] !== undefined) {
  52029. this._setValue(target, this._originalValue[index], -1);
  52030. }
  52031. index++;
  52032. }
  52033. }
  52034. else {
  52035. if (this._originalValue[0] !== undefined) {
  52036. this._setValue(this._target, this._originalValue[0], -1);
  52037. }
  52038. }
  52039. }
  52040. this._offsetsCache = {};
  52041. this._highLimitsCache = {};
  52042. this._currentFrame = 0;
  52043. this._blendingFactor = 0;
  52044. this._originalValue = new Array();
  52045. // Events
  52046. for (var index = 0; index < this._events.length; index++) {
  52047. this._events[index].isDone = false;
  52048. }
  52049. };
  52050. /**
  52051. * Specifies if the runtime animation is stopped
  52052. * @returns Boolean specifying if the runtime animation is stopped
  52053. */
  52054. RuntimeAnimation.prototype.isStopped = function () {
  52055. return this._stopped;
  52056. };
  52057. /**
  52058. * Disposes of the runtime animation
  52059. */
  52060. RuntimeAnimation.prototype.dispose = function () {
  52061. var index = this._animation.runtimeAnimations.indexOf(this);
  52062. if (index > -1) {
  52063. this._animation.runtimeAnimations.splice(index, 1);
  52064. }
  52065. };
  52066. /**
  52067. * Interpolates the animation from the current frame
  52068. * @param currentFrame The frame to interpolate the animation to
  52069. * @param repeatCount The number of times that the animation should loop
  52070. * @param loopMode The type of looping mode to use
  52071. * @param offsetValue Animation offset value
  52072. * @param highLimitValue The high limit value
  52073. * @returns The interpolated value
  52074. */
  52075. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52076. this._currentFrame = currentFrame;
  52077. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52078. this._workValue = BABYLON.Matrix.Zero();
  52079. }
  52080. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52081. };
  52082. /**
  52083. * Apply the interpolated value to the target
  52084. * @param currentValue defines the value computed by the animation
  52085. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52086. */
  52087. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52088. if (weight === void 0) { weight = 1.0; }
  52089. if (this._target instanceof Array) {
  52090. var index = 0;
  52091. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52092. var target = _a[_i];
  52093. this._setValue(target, currentValue, weight, index);
  52094. index++;
  52095. }
  52096. }
  52097. else {
  52098. this._setValue(this._target, currentValue, weight);
  52099. }
  52100. };
  52101. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52102. if (targetIndex === void 0) { targetIndex = 0; }
  52103. // Set value
  52104. var path;
  52105. var destination;
  52106. var targetPropertyPath = this._animation.targetPropertyPath;
  52107. if (targetPropertyPath.length > 1) {
  52108. var property = target[targetPropertyPath[0]];
  52109. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52110. property = property[targetPropertyPath[index]];
  52111. }
  52112. path = targetPropertyPath[targetPropertyPath.length - 1];
  52113. destination = property;
  52114. }
  52115. else {
  52116. path = targetPropertyPath[0];
  52117. destination = target;
  52118. }
  52119. this._targetPath = path;
  52120. this._activeTarget = destination;
  52121. this._weight = weight;
  52122. if (this._originalValue[targetIndex] === undefined) {
  52123. var originalValue = void 0;
  52124. if (destination.getRestPose && path === "_matrix") { // For bones
  52125. originalValue = destination.getRestPose();
  52126. }
  52127. else {
  52128. originalValue = destination[path];
  52129. }
  52130. if (originalValue && originalValue.clone) {
  52131. this._originalValue[targetIndex] = originalValue.clone();
  52132. }
  52133. else {
  52134. this._originalValue[targetIndex] = originalValue;
  52135. }
  52136. }
  52137. // Blending
  52138. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52139. if (enableBlending && this._blendingFactor <= 1.0) {
  52140. if (!this._originalBlendValue) {
  52141. var originalValue = destination[path];
  52142. if (originalValue.clone) {
  52143. this._originalBlendValue = originalValue.clone();
  52144. }
  52145. else {
  52146. this._originalBlendValue = originalValue;
  52147. }
  52148. }
  52149. if (this._originalBlendValue.m) { // Matrix
  52150. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52151. if (this._currentValue) {
  52152. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52153. }
  52154. else {
  52155. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52156. }
  52157. }
  52158. else {
  52159. if (this._currentValue) {
  52160. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52161. }
  52162. else {
  52163. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52164. }
  52165. }
  52166. }
  52167. else {
  52168. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52169. }
  52170. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52171. this._blendingFactor += blendingSpeed;
  52172. }
  52173. else {
  52174. this._currentValue = currentValue;
  52175. }
  52176. if (weight !== -1.0) {
  52177. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52178. }
  52179. else {
  52180. destination[path] = this._currentValue;
  52181. }
  52182. if (target.markAsDirty) {
  52183. target.markAsDirty(this._animation.targetProperty);
  52184. }
  52185. };
  52186. /**
  52187. * Gets the loop pmode of the runtime animation
  52188. * @returns Loop Mode
  52189. */
  52190. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52191. if (this._target && this._target.animationPropertiesOverride) {
  52192. return this._target.animationPropertiesOverride.loopMode;
  52193. }
  52194. return this._animation.loopMode;
  52195. };
  52196. /**
  52197. * Move the current animation to a given frame
  52198. * @param frame defines the frame to move to
  52199. */
  52200. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52201. var keys = this._animation.getKeys();
  52202. if (frame < keys[0].frame) {
  52203. frame = keys[0].frame;
  52204. }
  52205. else if (frame > keys[keys.length - 1].frame) {
  52206. frame = keys[keys.length - 1].frame;
  52207. }
  52208. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52209. this.setValue(currentValue, -1);
  52210. };
  52211. /**
  52212. * @hidden Internal use only
  52213. */
  52214. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52215. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52216. this._ratioOffset = this._previousRatio - newRatio;
  52217. };
  52218. /**
  52219. * Execute the current animation
  52220. * @param delay defines the delay to add to the current frame
  52221. * @param from defines the lower bound of the animation range
  52222. * @param to defines the upper bound of the animation range
  52223. * @param loop defines if the current animation must loop
  52224. * @param speedRatio defines the current speed ratio
  52225. * @param weight defines the weight of the animation (default is -1 so no weight)
  52226. * @returns a boolean indicating if the animation is running
  52227. */
  52228. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52229. if (weight === void 0) { weight = -1.0; }
  52230. var targetPropertyPath = this._animation.targetPropertyPath;
  52231. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52232. this._stopped = true;
  52233. return false;
  52234. }
  52235. var returnValue = true;
  52236. var keys = this._animation.getKeys();
  52237. // Adding a start key at frame 0 if missing
  52238. if (keys[0].frame !== 0) {
  52239. var newKey = { frame: 0, value: keys[0].value };
  52240. keys.splice(0, 0, newKey);
  52241. }
  52242. // Adding a duplicate key when there is only one key at frame zero
  52243. else if (keys.length === 1) {
  52244. var newKey = { frame: 0.001, value: keys[0].value };
  52245. keys.push(newKey);
  52246. }
  52247. // Check limits
  52248. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52249. from = keys[0].frame;
  52250. }
  52251. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52252. to = keys[keys.length - 1].frame;
  52253. }
  52254. //to and from cannot be the same key
  52255. if (from === to) {
  52256. if (from > keys[0].frame) {
  52257. from--;
  52258. }
  52259. else if (to < keys[keys.length - 1].frame) {
  52260. to++;
  52261. }
  52262. }
  52263. // Compute ratio
  52264. var range = to - from;
  52265. var offsetValue;
  52266. // ratio represents the frame delta between from and to
  52267. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52268. var highLimitValue = 0;
  52269. this._previousDelay = delay;
  52270. this._previousRatio = ratio;
  52271. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52272. returnValue = false;
  52273. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52274. }
  52275. else {
  52276. // Get max value if required
  52277. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52278. var keyOffset = to.toString() + from.toString();
  52279. if (!this._offsetsCache[keyOffset]) {
  52280. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52281. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52282. switch (this._animation.dataType) {
  52283. // Float
  52284. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52285. this._offsetsCache[keyOffset] = toValue - fromValue;
  52286. break;
  52287. // Quaternion
  52288. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52289. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52290. break;
  52291. // Vector3
  52292. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52293. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52294. // Vector2
  52295. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52296. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52297. // Size
  52298. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52299. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52300. // Color3
  52301. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52302. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52303. default:
  52304. break;
  52305. }
  52306. this._highLimitsCache[keyOffset] = toValue;
  52307. }
  52308. highLimitValue = this._highLimitsCache[keyOffset];
  52309. offsetValue = this._offsetsCache[keyOffset];
  52310. }
  52311. }
  52312. if (offsetValue === undefined) {
  52313. switch (this._animation.dataType) {
  52314. // Float
  52315. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52316. offsetValue = 0;
  52317. break;
  52318. // Quaternion
  52319. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52320. offsetValue = _staticOffsetValueQuaternion;
  52321. break;
  52322. // Vector3
  52323. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52324. offsetValue = _staticOffsetValueVector3;
  52325. break;
  52326. // Vector2
  52327. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52328. offsetValue = _staticOffsetValueVector2;
  52329. break;
  52330. // Size
  52331. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52332. offsetValue = _staticOffsetValueSize;
  52333. break;
  52334. // Color3
  52335. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52336. offsetValue = _staticOffsetValueColor3;
  52337. }
  52338. }
  52339. // Compute value
  52340. var repeatCount = (ratio / range) >> 0;
  52341. var currentFrame = returnValue ? from + ratio % range : to;
  52342. // Need to normalize?
  52343. if (this._host && this._host.syncRoot) {
  52344. var syncRoot = this._host.syncRoot;
  52345. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52346. currentFrame = from + (to - from) * hostNormalizedFrame;
  52347. }
  52348. // Reset events if looping
  52349. var events = this._events;
  52350. if (range > 0 && this.currentFrame > currentFrame ||
  52351. range < 0 && this.currentFrame < currentFrame) {
  52352. // Need to reset animation events
  52353. for (var index = 0; index < events.length; index++) {
  52354. if (!events[index].onlyOnce) {
  52355. // reset event, the animation is looping
  52356. events[index].isDone = false;
  52357. }
  52358. }
  52359. }
  52360. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52361. // Set value
  52362. this.setValue(currentValue, weight);
  52363. // Check events
  52364. for (var index = 0; index < events.length; index++) {
  52365. // Make sure current frame has passed event frame and that event frame is within the current range
  52366. // Also, handle both forward and reverse animations
  52367. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52368. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52369. var event = events[index];
  52370. if (!event.isDone) {
  52371. // If event should be done only once, remove it.
  52372. if (event.onlyOnce) {
  52373. events.splice(index, 1);
  52374. index--;
  52375. }
  52376. event.isDone = true;
  52377. event.action(currentFrame);
  52378. } // Don't do anything if the event has already be done.
  52379. }
  52380. }
  52381. if (!returnValue) {
  52382. this._stopped = true;
  52383. }
  52384. return returnValue;
  52385. };
  52386. return RuntimeAnimation;
  52387. }());
  52388. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52389. })(BABYLON || (BABYLON = {}));
  52390. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52391. var BABYLON;
  52392. (function (BABYLON) {
  52393. /**
  52394. * Class used to store an actual running animation
  52395. */
  52396. var Animatable = /** @class */ (function () {
  52397. /**
  52398. * Creates a new Animatable
  52399. * @param scene defines the hosting scene
  52400. * @param target defines the target object
  52401. * @param fromFrame defines the starting frame number (default is 0)
  52402. * @param toFrame defines the ending frame number (default is 100)
  52403. * @param loopAnimation defines if the animation must loop (default is false)
  52404. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52405. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52406. * @param animations defines a group of animation to add to the new Animatable
  52407. */
  52408. function Animatable(scene,
  52409. /** defines the target object */
  52410. target,
  52411. /** defines the starting frame number (default is 0) */
  52412. fromFrame,
  52413. /** defines the ending frame number (default is 100) */
  52414. toFrame,
  52415. /** defines if the animation must loop (default is false) */
  52416. loopAnimation, speedRatio,
  52417. /** defines a callback to call when animation ends if it is not looping */
  52418. onAnimationEnd, animations) {
  52419. if (fromFrame === void 0) { fromFrame = 0; }
  52420. if (toFrame === void 0) { toFrame = 100; }
  52421. if (loopAnimation === void 0) { loopAnimation = false; }
  52422. if (speedRatio === void 0) { speedRatio = 1.0; }
  52423. this.target = target;
  52424. this.fromFrame = fromFrame;
  52425. this.toFrame = toFrame;
  52426. this.loopAnimation = loopAnimation;
  52427. this.onAnimationEnd = onAnimationEnd;
  52428. this._localDelayOffset = null;
  52429. this._pausedDelay = null;
  52430. this._runtimeAnimations = new Array();
  52431. this._paused = false;
  52432. this._speedRatio = 1;
  52433. this._weight = -1.0;
  52434. /**
  52435. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52436. * This will only apply for non looping animation (default is true)
  52437. */
  52438. this.disposeOnEnd = true;
  52439. /**
  52440. * Gets a boolean indicating if the animation has started
  52441. */
  52442. this.animationStarted = false;
  52443. /**
  52444. * Observer raised when the animation ends
  52445. */
  52446. this.onAnimationEndObservable = new BABYLON.Observable();
  52447. this._scene = scene;
  52448. if (animations) {
  52449. this.appendAnimations(target, animations);
  52450. }
  52451. this._speedRatio = speedRatio;
  52452. scene._activeAnimatables.push(this);
  52453. }
  52454. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52455. /**
  52456. * Gets the root Animatable used to synchronize and normalize animations
  52457. */
  52458. get: function () {
  52459. return this._syncRoot;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52465. /**
  52466. * Gets the current frame of the first RuntimeAnimation
  52467. * Used to synchronize Animatables
  52468. */
  52469. get: function () {
  52470. if (this._runtimeAnimations.length === 0) {
  52471. return 0;
  52472. }
  52473. return this._runtimeAnimations[0].currentFrame;
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. Object.defineProperty(Animatable.prototype, "weight", {
  52479. /**
  52480. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52481. */
  52482. get: function () {
  52483. return this._weight;
  52484. },
  52485. set: function (value) {
  52486. if (value === -1) { // -1 is ok and means no weight
  52487. this._weight = -1;
  52488. return;
  52489. }
  52490. // Else weight must be in [0, 1] range
  52491. this._weight = Math.min(Math.max(value, 0), 1.0);
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52497. /**
  52498. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52499. */
  52500. get: function () {
  52501. return this._speedRatio;
  52502. },
  52503. set: function (value) {
  52504. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52505. var animation = this._runtimeAnimations[index];
  52506. animation._prepareForSpeedRatioChange(value);
  52507. }
  52508. this._speedRatio = value;
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. // Methods
  52514. /**
  52515. * Synchronize and normalize current Animatable with a source Animatable
  52516. * This is useful when using animation weights and when animations are not of the same length
  52517. * @param root defines the root Animatable to synchronize with
  52518. * @returns the current Animatable
  52519. */
  52520. Animatable.prototype.syncWith = function (root) {
  52521. this._syncRoot = root;
  52522. if (root) {
  52523. // Make sure this animatable will animate after the root
  52524. var index = this._scene._activeAnimatables.indexOf(this);
  52525. if (index > -1) {
  52526. this._scene._activeAnimatables.splice(index, 1);
  52527. this._scene._activeAnimatables.push(this);
  52528. }
  52529. }
  52530. return this;
  52531. };
  52532. /**
  52533. * Gets the list of runtime animations
  52534. * @returns an array of RuntimeAnimation
  52535. */
  52536. Animatable.prototype.getAnimations = function () {
  52537. return this._runtimeAnimations;
  52538. };
  52539. /**
  52540. * Adds more animations to the current animatable
  52541. * @param target defines the target of the animations
  52542. * @param animations defines the new animations to add
  52543. */
  52544. Animatable.prototype.appendAnimations = function (target, animations) {
  52545. for (var index = 0; index < animations.length; index++) {
  52546. var animation = animations[index];
  52547. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52548. }
  52549. };
  52550. /**
  52551. * Gets the source animation for a specific property
  52552. * @param property defines the propertyu to look for
  52553. * @returns null or the source animation for the given property
  52554. */
  52555. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52556. var runtimeAnimations = this._runtimeAnimations;
  52557. for (var index = 0; index < runtimeAnimations.length; index++) {
  52558. if (runtimeAnimations[index].animation.targetProperty === property) {
  52559. return runtimeAnimations[index].animation;
  52560. }
  52561. }
  52562. return null;
  52563. };
  52564. /**
  52565. * Gets the runtime animation for a specific property
  52566. * @param property defines the propertyu to look for
  52567. * @returns null or the runtime animation for the given property
  52568. */
  52569. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52570. var runtimeAnimations = this._runtimeAnimations;
  52571. for (var index = 0; index < runtimeAnimations.length; index++) {
  52572. if (runtimeAnimations[index].animation.targetProperty === property) {
  52573. return runtimeAnimations[index];
  52574. }
  52575. }
  52576. return null;
  52577. };
  52578. /**
  52579. * Resets the animatable to its original state
  52580. */
  52581. Animatable.prototype.reset = function () {
  52582. var runtimeAnimations = this._runtimeAnimations;
  52583. for (var index = 0; index < runtimeAnimations.length; index++) {
  52584. runtimeAnimations[index].reset(true);
  52585. }
  52586. this._localDelayOffset = null;
  52587. this._pausedDelay = null;
  52588. };
  52589. /**
  52590. * Allows the animatable to blend with current running animations
  52591. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52592. * @param blendingSpeed defines the blending speed to use
  52593. */
  52594. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52595. var runtimeAnimations = this._runtimeAnimations;
  52596. for (var index = 0; index < runtimeAnimations.length; index++) {
  52597. runtimeAnimations[index].animation.enableBlending = true;
  52598. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52599. }
  52600. };
  52601. /**
  52602. * Disable animation blending
  52603. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52604. */
  52605. Animatable.prototype.disableBlending = function () {
  52606. var runtimeAnimations = this._runtimeAnimations;
  52607. for (var index = 0; index < runtimeAnimations.length; index++) {
  52608. runtimeAnimations[index].animation.enableBlending = false;
  52609. }
  52610. };
  52611. /**
  52612. * Jump directly to a given frame
  52613. * @param frame defines the frame to jump to
  52614. */
  52615. Animatable.prototype.goToFrame = function (frame) {
  52616. var runtimeAnimations = this._runtimeAnimations;
  52617. if (runtimeAnimations[0]) {
  52618. var fps = runtimeAnimations[0].animation.framePerSecond;
  52619. var currentFrame = runtimeAnimations[0].currentFrame;
  52620. var adjustTime = frame - currentFrame;
  52621. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52622. if (this._localDelayOffset === null) {
  52623. this._localDelayOffset = 0;
  52624. }
  52625. this._localDelayOffset -= delay;
  52626. }
  52627. for (var index = 0; index < runtimeAnimations.length; index++) {
  52628. runtimeAnimations[index].goToFrame(frame);
  52629. }
  52630. };
  52631. /**
  52632. * Pause the animation
  52633. */
  52634. Animatable.prototype.pause = function () {
  52635. if (this._paused) {
  52636. return;
  52637. }
  52638. this._paused = true;
  52639. };
  52640. /**
  52641. * Restart the animation
  52642. */
  52643. Animatable.prototype.restart = function () {
  52644. this._paused = false;
  52645. };
  52646. Animatable.prototype._raiseOnAnimationEnd = function () {
  52647. if (this.onAnimationEnd) {
  52648. this.onAnimationEnd();
  52649. }
  52650. this.onAnimationEndObservable.notifyObservers(this);
  52651. };
  52652. /**
  52653. * Stop and delete the current animation
  52654. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52655. * @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)
  52656. */
  52657. Animatable.prototype.stop = function (animationName, targetMask) {
  52658. if (animationName || targetMask) {
  52659. var idx = this._scene._activeAnimatables.indexOf(this);
  52660. if (idx > -1) {
  52661. var runtimeAnimations = this._runtimeAnimations;
  52662. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52663. var runtimeAnimation = runtimeAnimations[index];
  52664. if (animationName && runtimeAnimation.animation.name != animationName) {
  52665. continue;
  52666. }
  52667. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52668. continue;
  52669. }
  52670. runtimeAnimation.dispose();
  52671. runtimeAnimations.splice(index, 1);
  52672. }
  52673. if (runtimeAnimations.length == 0) {
  52674. this._scene._activeAnimatables.splice(idx, 1);
  52675. this._raiseOnAnimationEnd();
  52676. }
  52677. }
  52678. }
  52679. else {
  52680. var index = this._scene._activeAnimatables.indexOf(this);
  52681. if (index > -1) {
  52682. this._scene._activeAnimatables.splice(index, 1);
  52683. var runtimeAnimations = this._runtimeAnimations;
  52684. for (var index = 0; index < runtimeAnimations.length; index++) {
  52685. runtimeAnimations[index].dispose();
  52686. }
  52687. this._raiseOnAnimationEnd();
  52688. }
  52689. }
  52690. };
  52691. /**
  52692. * Wait asynchronously for the animation to end
  52693. * @returns a promise which will be fullfilled when the animation ends
  52694. */
  52695. Animatable.prototype.waitAsync = function () {
  52696. var _this = this;
  52697. return new Promise(function (resolve, reject) {
  52698. _this.onAnimationEndObservable.add(function () {
  52699. resolve(_this);
  52700. }, undefined, undefined, _this, true);
  52701. });
  52702. };
  52703. /** @hidden */
  52704. Animatable.prototype._animate = function (delay) {
  52705. if (this._paused) {
  52706. this.animationStarted = false;
  52707. if (this._pausedDelay === null) {
  52708. this._pausedDelay = delay;
  52709. }
  52710. return true;
  52711. }
  52712. if (this._localDelayOffset === null) {
  52713. this._localDelayOffset = delay;
  52714. this._pausedDelay = null;
  52715. }
  52716. else if (this._pausedDelay !== null) {
  52717. this._localDelayOffset += delay - this._pausedDelay;
  52718. this._pausedDelay = null;
  52719. }
  52720. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52721. return true;
  52722. }
  52723. // Animating
  52724. var running = false;
  52725. var runtimeAnimations = this._runtimeAnimations;
  52726. var index;
  52727. for (index = 0; index < runtimeAnimations.length; index++) {
  52728. var animation = runtimeAnimations[index];
  52729. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52730. running = running || isRunning;
  52731. }
  52732. this.animationStarted = running;
  52733. if (!running) {
  52734. if (this.disposeOnEnd) {
  52735. // Remove from active animatables
  52736. index = this._scene._activeAnimatables.indexOf(this);
  52737. this._scene._activeAnimatables.splice(index, 1);
  52738. // Dispose all runtime animations
  52739. for (index = 0; index < runtimeAnimations.length; index++) {
  52740. runtimeAnimations[index].dispose();
  52741. }
  52742. }
  52743. this._raiseOnAnimationEnd();
  52744. if (this.disposeOnEnd) {
  52745. this.onAnimationEnd = null;
  52746. this.onAnimationEndObservable.clear();
  52747. }
  52748. }
  52749. return running;
  52750. };
  52751. return Animatable;
  52752. }());
  52753. BABYLON.Animatable = Animatable;
  52754. })(BABYLON || (BABYLON = {}));
  52755. //# sourceMappingURL=babylon.animatable.js.map
  52756. var BABYLON;
  52757. (function (BABYLON) {
  52758. /**
  52759. * Base class used for every default easing function.
  52760. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52761. */
  52762. var EasingFunction = /** @class */ (function () {
  52763. function EasingFunction() {
  52764. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52765. }
  52766. /**
  52767. * Sets the easing mode of the current function.
  52768. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52769. */
  52770. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52771. var n = Math.min(Math.max(easingMode, 0), 2);
  52772. this._easingMode = n;
  52773. };
  52774. /**
  52775. * Gets the current easing mode.
  52776. * @returns the easing mode
  52777. */
  52778. EasingFunction.prototype.getEasingMode = function () {
  52779. return this._easingMode;
  52780. };
  52781. /**
  52782. * @hidden
  52783. */
  52784. EasingFunction.prototype.easeInCore = function (gradient) {
  52785. throw new Error('You must implement this method');
  52786. };
  52787. /**
  52788. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52789. * of the easing function.
  52790. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52791. * @returns the corresponding value on the curve defined by the easing function
  52792. */
  52793. EasingFunction.prototype.ease = function (gradient) {
  52794. switch (this._easingMode) {
  52795. case EasingFunction.EASINGMODE_EASEIN:
  52796. return this.easeInCore(gradient);
  52797. case EasingFunction.EASINGMODE_EASEOUT:
  52798. return (1 - this.easeInCore(1 - gradient));
  52799. }
  52800. if (gradient >= 0.5) {
  52801. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52802. }
  52803. return (this.easeInCore(gradient * 2) * 0.5);
  52804. };
  52805. /**
  52806. * Interpolation follows the mathematical formula associated with the easing function.
  52807. */
  52808. EasingFunction.EASINGMODE_EASEIN = 0;
  52809. /**
  52810. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52811. */
  52812. EasingFunction.EASINGMODE_EASEOUT = 1;
  52813. /**
  52814. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52815. */
  52816. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52817. return EasingFunction;
  52818. }());
  52819. BABYLON.EasingFunction = EasingFunction;
  52820. /**
  52821. * Easing function with a circle shape (see link below).
  52822. * @see https://easings.net/#easeInCirc
  52823. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52824. */
  52825. var CircleEase = /** @class */ (function (_super) {
  52826. __extends(CircleEase, _super);
  52827. function CircleEase() {
  52828. return _super !== null && _super.apply(this, arguments) || this;
  52829. }
  52830. /** @hidden */
  52831. CircleEase.prototype.easeInCore = function (gradient) {
  52832. gradient = Math.max(0, Math.min(1, gradient));
  52833. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52834. };
  52835. return CircleEase;
  52836. }(EasingFunction));
  52837. BABYLON.CircleEase = CircleEase;
  52838. /**
  52839. * Easing function with a ease back shape (see link below).
  52840. * @see https://easings.net/#easeInBack
  52841. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52842. */
  52843. var BackEase = /** @class */ (function (_super) {
  52844. __extends(BackEase, _super);
  52845. /**
  52846. * Instantiates a back ease easing
  52847. * @see https://easings.net/#easeInBack
  52848. * @param amplitude Defines the amplitude of the function
  52849. */
  52850. function BackEase(
  52851. /** Defines the amplitude of the function */
  52852. amplitude) {
  52853. if (amplitude === void 0) { amplitude = 1; }
  52854. var _this = _super.call(this) || this;
  52855. _this.amplitude = amplitude;
  52856. return _this;
  52857. }
  52858. /** @hidden */
  52859. BackEase.prototype.easeInCore = function (gradient) {
  52860. var num = Math.max(0, this.amplitude);
  52861. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52862. };
  52863. return BackEase;
  52864. }(EasingFunction));
  52865. BABYLON.BackEase = BackEase;
  52866. /**
  52867. * Easing function with a bouncing shape (see link below).
  52868. * @see https://easings.net/#easeInBounce
  52869. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52870. */
  52871. var BounceEase = /** @class */ (function (_super) {
  52872. __extends(BounceEase, _super);
  52873. /**
  52874. * Instantiates a bounce easing
  52875. * @see https://easings.net/#easeInBounce
  52876. * @param bounces Defines the number of bounces
  52877. * @param bounciness Defines the amplitude of the bounce
  52878. */
  52879. function BounceEase(
  52880. /** Defines the number of bounces */
  52881. bounces,
  52882. /** Defines the amplitude of the bounce */
  52883. bounciness) {
  52884. if (bounces === void 0) { bounces = 3; }
  52885. if (bounciness === void 0) { bounciness = 2; }
  52886. var _this = _super.call(this) || this;
  52887. _this.bounces = bounces;
  52888. _this.bounciness = bounciness;
  52889. return _this;
  52890. }
  52891. /** @hidden */
  52892. BounceEase.prototype.easeInCore = function (gradient) {
  52893. var y = Math.max(0.0, this.bounces);
  52894. var bounciness = this.bounciness;
  52895. if (bounciness <= 1.0) {
  52896. bounciness = 1.001;
  52897. }
  52898. var num9 = Math.pow(bounciness, y);
  52899. var num5 = 1.0 - bounciness;
  52900. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52901. var num15 = gradient * num4;
  52902. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52903. var num3 = Math.floor(num65);
  52904. var num13 = num3 + 1.0;
  52905. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52906. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52907. var num7 = (num8 + num12) * 0.5;
  52908. var num6 = gradient - num7;
  52909. var num2 = num7 - num8;
  52910. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52911. };
  52912. return BounceEase;
  52913. }(EasingFunction));
  52914. BABYLON.BounceEase = BounceEase;
  52915. /**
  52916. * Easing function with a power of 3 shape (see link below).
  52917. * @see https://easings.net/#easeInCubic
  52918. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52919. */
  52920. var CubicEase = /** @class */ (function (_super) {
  52921. __extends(CubicEase, _super);
  52922. function CubicEase() {
  52923. return _super !== null && _super.apply(this, arguments) || this;
  52924. }
  52925. /** @hidden */
  52926. CubicEase.prototype.easeInCore = function (gradient) {
  52927. return (gradient * gradient * gradient);
  52928. };
  52929. return CubicEase;
  52930. }(EasingFunction));
  52931. BABYLON.CubicEase = CubicEase;
  52932. /**
  52933. * Easing function with an elastic shape (see link below).
  52934. * @see https://easings.net/#easeInElastic
  52935. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52936. */
  52937. var ElasticEase = /** @class */ (function (_super) {
  52938. __extends(ElasticEase, _super);
  52939. /**
  52940. * Instantiates an elastic easing function
  52941. * @see https://easings.net/#easeInElastic
  52942. * @param oscillations Defines the number of oscillations
  52943. * @param springiness Defines the amplitude of the oscillations
  52944. */
  52945. function ElasticEase(
  52946. /** Defines the number of oscillations*/
  52947. oscillations,
  52948. /** Defines the amplitude of the oscillations*/
  52949. springiness) {
  52950. if (oscillations === void 0) { oscillations = 3; }
  52951. if (springiness === void 0) { springiness = 3; }
  52952. var _this = _super.call(this) || this;
  52953. _this.oscillations = oscillations;
  52954. _this.springiness = springiness;
  52955. return _this;
  52956. }
  52957. /** @hidden */
  52958. ElasticEase.prototype.easeInCore = function (gradient) {
  52959. var num2;
  52960. var num3 = Math.max(0.0, this.oscillations);
  52961. var num = Math.max(0.0, this.springiness);
  52962. if (num == 0) {
  52963. num2 = gradient;
  52964. }
  52965. else {
  52966. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52967. }
  52968. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52969. };
  52970. return ElasticEase;
  52971. }(EasingFunction));
  52972. BABYLON.ElasticEase = ElasticEase;
  52973. /**
  52974. * Easing function with an exponential shape (see link below).
  52975. * @see https://easings.net/#easeInExpo
  52976. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52977. */
  52978. var ExponentialEase = /** @class */ (function (_super) {
  52979. __extends(ExponentialEase, _super);
  52980. /**
  52981. * Instantiates an exponential easing function
  52982. * @see https://easings.net/#easeInExpo
  52983. * @param exponent Defines the exponent of the function
  52984. */
  52985. function ExponentialEase(
  52986. /** Defines the exponent of the function */
  52987. exponent) {
  52988. if (exponent === void 0) { exponent = 2; }
  52989. var _this = _super.call(this) || this;
  52990. _this.exponent = exponent;
  52991. return _this;
  52992. }
  52993. /** @hidden */
  52994. ExponentialEase.prototype.easeInCore = function (gradient) {
  52995. if (this.exponent <= 0) {
  52996. return gradient;
  52997. }
  52998. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52999. };
  53000. return ExponentialEase;
  53001. }(EasingFunction));
  53002. BABYLON.ExponentialEase = ExponentialEase;
  53003. /**
  53004. * Easing function with a power shape (see link below).
  53005. * @see https://easings.net/#easeInQuad
  53006. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53007. */
  53008. var PowerEase = /** @class */ (function (_super) {
  53009. __extends(PowerEase, _super);
  53010. /**
  53011. * Instantiates an power base easing function
  53012. * @see https://easings.net/#easeInQuad
  53013. * @param power Defines the power of the function
  53014. */
  53015. function PowerEase(
  53016. /** Defines the power of the function */
  53017. power) {
  53018. if (power === void 0) { power = 2; }
  53019. var _this = _super.call(this) || this;
  53020. _this.power = power;
  53021. return _this;
  53022. }
  53023. /** @hidden */
  53024. PowerEase.prototype.easeInCore = function (gradient) {
  53025. var y = Math.max(0.0, this.power);
  53026. return Math.pow(gradient, y);
  53027. };
  53028. return PowerEase;
  53029. }(EasingFunction));
  53030. BABYLON.PowerEase = PowerEase;
  53031. /**
  53032. * Easing function with a power of 2 shape (see link below).
  53033. * @see https://easings.net/#easeInQuad
  53034. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53035. */
  53036. var QuadraticEase = /** @class */ (function (_super) {
  53037. __extends(QuadraticEase, _super);
  53038. function QuadraticEase() {
  53039. return _super !== null && _super.apply(this, arguments) || this;
  53040. }
  53041. /** @hidden */
  53042. QuadraticEase.prototype.easeInCore = function (gradient) {
  53043. return (gradient * gradient);
  53044. };
  53045. return QuadraticEase;
  53046. }(EasingFunction));
  53047. BABYLON.QuadraticEase = QuadraticEase;
  53048. /**
  53049. * Easing function with a power of 4 shape (see link below).
  53050. * @see https://easings.net/#easeInQuart
  53051. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53052. */
  53053. var QuarticEase = /** @class */ (function (_super) {
  53054. __extends(QuarticEase, _super);
  53055. function QuarticEase() {
  53056. return _super !== null && _super.apply(this, arguments) || this;
  53057. }
  53058. /** @hidden */
  53059. QuarticEase.prototype.easeInCore = function (gradient) {
  53060. return (gradient * gradient * gradient * gradient);
  53061. };
  53062. return QuarticEase;
  53063. }(EasingFunction));
  53064. BABYLON.QuarticEase = QuarticEase;
  53065. /**
  53066. * Easing function with a power of 5 shape (see link below).
  53067. * @see https://easings.net/#easeInQuint
  53068. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53069. */
  53070. var QuinticEase = /** @class */ (function (_super) {
  53071. __extends(QuinticEase, _super);
  53072. function QuinticEase() {
  53073. return _super !== null && _super.apply(this, arguments) || this;
  53074. }
  53075. /** @hidden */
  53076. QuinticEase.prototype.easeInCore = function (gradient) {
  53077. return (gradient * gradient * gradient * gradient * gradient);
  53078. };
  53079. return QuinticEase;
  53080. }(EasingFunction));
  53081. BABYLON.QuinticEase = QuinticEase;
  53082. /**
  53083. * Easing function with a sin shape (see link below).
  53084. * @see https://easings.net/#easeInSine
  53085. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53086. */
  53087. var SineEase = /** @class */ (function (_super) {
  53088. __extends(SineEase, _super);
  53089. function SineEase() {
  53090. return _super !== null && _super.apply(this, arguments) || this;
  53091. }
  53092. /** @hidden */
  53093. SineEase.prototype.easeInCore = function (gradient) {
  53094. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53095. };
  53096. return SineEase;
  53097. }(EasingFunction));
  53098. BABYLON.SineEase = SineEase;
  53099. /**
  53100. * Easing function with a bezier shape (see link below).
  53101. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53102. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53103. */
  53104. var BezierCurveEase = /** @class */ (function (_super) {
  53105. __extends(BezierCurveEase, _super);
  53106. /**
  53107. * Instantiates a bezier function
  53108. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53109. * @param x1 Defines the x component of the start tangent in the bezier curve
  53110. * @param y1 Defines the y component of the start tangent in the bezier curve
  53111. * @param x2 Defines the x component of the end tangent in the bezier curve
  53112. * @param y2 Defines the y component of the end tangent in the bezier curve
  53113. */
  53114. function BezierCurveEase(
  53115. /** Defines the x component of the start tangent in the bezier curve */
  53116. x1,
  53117. /** Defines the y component of the start tangent in the bezier curve */
  53118. y1,
  53119. /** Defines the x component of the end tangent in the bezier curve */
  53120. x2,
  53121. /** Defines the y component of the end tangent in the bezier curve */
  53122. y2) {
  53123. if (x1 === void 0) { x1 = 0; }
  53124. if (y1 === void 0) { y1 = 0; }
  53125. if (x2 === void 0) { x2 = 1; }
  53126. if (y2 === void 0) { y2 = 1; }
  53127. var _this = _super.call(this) || this;
  53128. _this.x1 = x1;
  53129. _this.y1 = y1;
  53130. _this.x2 = x2;
  53131. _this.y2 = y2;
  53132. return _this;
  53133. }
  53134. /** @hidden */
  53135. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53136. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53137. };
  53138. return BezierCurveEase;
  53139. }(EasingFunction));
  53140. BABYLON.BezierCurveEase = BezierCurveEase;
  53141. })(BABYLON || (BABYLON = {}));
  53142. //# sourceMappingURL=babylon.easing.js.map
  53143. var BABYLON;
  53144. (function (BABYLON) {
  53145. /**
  53146. * A Condition applied to an Action
  53147. */
  53148. var Condition = /** @class */ (function () {
  53149. /**
  53150. * Creates a new Condition
  53151. * @param actionManager the manager of the action the condition is applied to
  53152. */
  53153. function Condition(actionManager) {
  53154. this._actionManager = actionManager;
  53155. }
  53156. /**
  53157. * Check if the current condition is valid
  53158. * @returns a boolean
  53159. */
  53160. Condition.prototype.isValid = function () {
  53161. return true;
  53162. };
  53163. /**
  53164. * Internal only
  53165. * @hidden
  53166. */
  53167. Condition.prototype._getProperty = function (propertyPath) {
  53168. return this._actionManager._getProperty(propertyPath);
  53169. };
  53170. /**
  53171. * Internal only
  53172. * @hidden
  53173. */
  53174. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53175. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53176. };
  53177. /**
  53178. * Serialize placeholder for child classes
  53179. * @returns the serialized object
  53180. */
  53181. Condition.prototype.serialize = function () {
  53182. };
  53183. /**
  53184. * Internal only
  53185. * @hidden
  53186. */
  53187. Condition.prototype._serialize = function (serializedCondition) {
  53188. return {
  53189. type: 2,
  53190. children: [],
  53191. name: serializedCondition.name,
  53192. properties: serializedCondition.properties
  53193. };
  53194. };
  53195. return Condition;
  53196. }());
  53197. BABYLON.Condition = Condition;
  53198. /**
  53199. * Defines specific conditional operators as extensions of Condition
  53200. */
  53201. var ValueCondition = /** @class */ (function (_super) {
  53202. __extends(ValueCondition, _super);
  53203. /**
  53204. * Creates a new ValueCondition
  53205. * @param actionManager manager for the action the condition applies to
  53206. * @param target for the action
  53207. * @param propertyPath path to specify the property of the target the conditional operator uses
  53208. * @param value the value compared by the conditional operator against the current value of the property
  53209. * @param operator the conditional operator, default ValueCondition.IsEqual
  53210. */
  53211. function ValueCondition(actionManager, target,
  53212. /** path to specify the property of the target the conditional operator uses */
  53213. propertyPath,
  53214. /** the value compared by the conditional operator against the current value of the property */
  53215. value,
  53216. /** the conditional operator, default ValueCondition.IsEqual */
  53217. operator) {
  53218. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53219. var _this = _super.call(this, actionManager) || this;
  53220. _this.propertyPath = propertyPath;
  53221. _this.value = value;
  53222. _this.operator = operator;
  53223. _this._target = target;
  53224. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53225. _this._property = _this._getProperty(_this.propertyPath);
  53226. return _this;
  53227. }
  53228. Object.defineProperty(ValueCondition, "IsEqual", {
  53229. /**
  53230. * returns the number for IsEqual
  53231. */
  53232. get: function () {
  53233. return ValueCondition._IsEqual;
  53234. },
  53235. enumerable: true,
  53236. configurable: true
  53237. });
  53238. Object.defineProperty(ValueCondition, "IsDifferent", {
  53239. /**
  53240. * Returns the number for IsDifferent
  53241. */
  53242. get: function () {
  53243. return ValueCondition._IsDifferent;
  53244. },
  53245. enumerable: true,
  53246. configurable: true
  53247. });
  53248. Object.defineProperty(ValueCondition, "IsGreater", {
  53249. /**
  53250. * Returns the number for IsGreater
  53251. */
  53252. get: function () {
  53253. return ValueCondition._IsGreater;
  53254. },
  53255. enumerable: true,
  53256. configurable: true
  53257. });
  53258. Object.defineProperty(ValueCondition, "IsLesser", {
  53259. /**
  53260. * Returns the number for IsLesser
  53261. */
  53262. get: function () {
  53263. return ValueCondition._IsLesser;
  53264. },
  53265. enumerable: true,
  53266. configurable: true
  53267. });
  53268. /**
  53269. * Compares the given value with the property value for the specified conditional operator
  53270. * @returns the result of the comparison
  53271. */
  53272. ValueCondition.prototype.isValid = function () {
  53273. switch (this.operator) {
  53274. case ValueCondition.IsGreater:
  53275. return this._effectiveTarget[this._property] > this.value;
  53276. case ValueCondition.IsLesser:
  53277. return this._effectiveTarget[this._property] < this.value;
  53278. case ValueCondition.IsEqual:
  53279. case ValueCondition.IsDifferent:
  53280. var check;
  53281. if (this.value.equals) {
  53282. check = this.value.equals(this._effectiveTarget[this._property]);
  53283. }
  53284. else {
  53285. check = this.value === this._effectiveTarget[this._property];
  53286. }
  53287. return this.operator === ValueCondition.IsEqual ? check : !check;
  53288. }
  53289. return false;
  53290. };
  53291. /**
  53292. * Serialize the ValueCondition into a JSON compatible object
  53293. * @returns serialization object
  53294. */
  53295. ValueCondition.prototype.serialize = function () {
  53296. return this._serialize({
  53297. name: "ValueCondition",
  53298. properties: [
  53299. BABYLON.Action._GetTargetProperty(this._target),
  53300. { name: "propertyPath", value: this.propertyPath },
  53301. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53302. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53303. ]
  53304. });
  53305. };
  53306. /**
  53307. * Gets the name of the conditional operator for the ValueCondition
  53308. * @param operator the conditional operator
  53309. * @returns the name
  53310. */
  53311. ValueCondition.GetOperatorName = function (operator) {
  53312. switch (operator) {
  53313. case ValueCondition._IsEqual: return "IsEqual";
  53314. case ValueCondition._IsDifferent: return "IsDifferent";
  53315. case ValueCondition._IsGreater: return "IsGreater";
  53316. case ValueCondition._IsLesser: return "IsLesser";
  53317. default: return "";
  53318. }
  53319. };
  53320. /**
  53321. * Internal only
  53322. * @hidden
  53323. */
  53324. ValueCondition._IsEqual = 0;
  53325. /**
  53326. * Internal only
  53327. * @hidden
  53328. */
  53329. ValueCondition._IsDifferent = 1;
  53330. /**
  53331. * Internal only
  53332. * @hidden
  53333. */
  53334. ValueCondition._IsGreater = 2;
  53335. /**
  53336. * Internal only
  53337. * @hidden
  53338. */
  53339. ValueCondition._IsLesser = 3;
  53340. return ValueCondition;
  53341. }(Condition));
  53342. BABYLON.ValueCondition = ValueCondition;
  53343. /**
  53344. * Defines a predicate condition as an extension of Condition
  53345. */
  53346. var PredicateCondition = /** @class */ (function (_super) {
  53347. __extends(PredicateCondition, _super);
  53348. /**
  53349. * Creates a new PredicateCondition
  53350. * @param actionManager manager for the action the condition applies to
  53351. * @param predicate defines the predicate function used to validate the condition
  53352. */
  53353. function PredicateCondition(actionManager,
  53354. /** defines the predicate function used to validate the condition */
  53355. predicate) {
  53356. var _this = _super.call(this, actionManager) || this;
  53357. _this.predicate = predicate;
  53358. return _this;
  53359. }
  53360. /**
  53361. * @returns the validity of the predicate condition
  53362. */
  53363. PredicateCondition.prototype.isValid = function () {
  53364. return this.predicate();
  53365. };
  53366. return PredicateCondition;
  53367. }(Condition));
  53368. BABYLON.PredicateCondition = PredicateCondition;
  53369. /**
  53370. * Defines a state condition as an extension of Condition
  53371. */
  53372. var StateCondition = /** @class */ (function (_super) {
  53373. __extends(StateCondition, _super);
  53374. /**
  53375. * Creates a new StateCondition
  53376. * @param actionManager manager for the action the condition applies to
  53377. * @param target of the condition
  53378. * @param value to compare with target state
  53379. */
  53380. function StateCondition(actionManager, target, value) {
  53381. var _this = _super.call(this, actionManager) || this;
  53382. _this.value = value;
  53383. _this._target = target;
  53384. return _this;
  53385. }
  53386. /**
  53387. * @returns the validity of the state
  53388. */
  53389. StateCondition.prototype.isValid = function () {
  53390. return this._target.state === this.value;
  53391. };
  53392. /**
  53393. * Serialize the StateCondition into a JSON compatible object
  53394. * @returns serialization object
  53395. */
  53396. StateCondition.prototype.serialize = function () {
  53397. return this._serialize({
  53398. name: "StateCondition",
  53399. properties: [
  53400. BABYLON.Action._GetTargetProperty(this._target),
  53401. { name: "value", value: this.value }
  53402. ]
  53403. });
  53404. };
  53405. return StateCondition;
  53406. }(Condition));
  53407. BABYLON.StateCondition = StateCondition;
  53408. })(BABYLON || (BABYLON = {}));
  53409. //# sourceMappingURL=babylon.condition.js.map
  53410. var BABYLON;
  53411. (function (BABYLON) {
  53412. /**
  53413. * The action to be carried out following a trigger
  53414. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53415. */
  53416. var Action = /** @class */ (function () {
  53417. /**
  53418. * Creates a new Action
  53419. * @param triggerOptions the trigger, with or without parameters, for the action
  53420. * @param condition an optional determinant of action
  53421. */
  53422. function Action(
  53423. /** the trigger, with or without parameters, for the action */
  53424. triggerOptions, condition) {
  53425. this.triggerOptions = triggerOptions;
  53426. /**
  53427. * An event triggered prior to action being executed.
  53428. */
  53429. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53430. if (triggerOptions.parameter) {
  53431. this.trigger = triggerOptions.trigger;
  53432. this._triggerParameter = triggerOptions.parameter;
  53433. }
  53434. else if (triggerOptions.trigger) {
  53435. this.trigger = triggerOptions.trigger;
  53436. }
  53437. else {
  53438. this.trigger = triggerOptions;
  53439. }
  53440. this._nextActiveAction = this;
  53441. this._condition = condition;
  53442. }
  53443. /**
  53444. * Internal only
  53445. * @hidden
  53446. */
  53447. Action.prototype._prepare = function () {
  53448. };
  53449. /**
  53450. * Gets the trigger parameters
  53451. * @returns the trigger parameters
  53452. */
  53453. Action.prototype.getTriggerParameter = function () {
  53454. return this._triggerParameter;
  53455. };
  53456. /**
  53457. * Internal only - executes current action event
  53458. * @hidden
  53459. */
  53460. Action.prototype._executeCurrent = function (evt) {
  53461. if (this._nextActiveAction._condition) {
  53462. var condition = this._nextActiveAction._condition;
  53463. var currentRenderId = this._actionManager.getScene().getRenderId();
  53464. // We cache the current evaluation for the current frame
  53465. if (condition._evaluationId === currentRenderId) {
  53466. if (!condition._currentResult) {
  53467. return;
  53468. }
  53469. }
  53470. else {
  53471. condition._evaluationId = currentRenderId;
  53472. if (!condition.isValid()) {
  53473. condition._currentResult = false;
  53474. return;
  53475. }
  53476. condition._currentResult = true;
  53477. }
  53478. }
  53479. this.onBeforeExecuteObservable.notifyObservers(this);
  53480. this._nextActiveAction.execute(evt);
  53481. this.skipToNextActiveAction();
  53482. };
  53483. /**
  53484. * Execute placeholder for child classes
  53485. * @param evt optional action event
  53486. */
  53487. Action.prototype.execute = function (evt) {
  53488. };
  53489. /**
  53490. * Skips to next active action
  53491. */
  53492. Action.prototype.skipToNextActiveAction = function () {
  53493. if (this._nextActiveAction._child) {
  53494. if (!this._nextActiveAction._child._actionManager) {
  53495. this._nextActiveAction._child._actionManager = this._actionManager;
  53496. }
  53497. this._nextActiveAction = this._nextActiveAction._child;
  53498. }
  53499. else {
  53500. this._nextActiveAction = this;
  53501. }
  53502. };
  53503. /**
  53504. * Adds action to chain of actions, may be a DoNothingAction
  53505. * @param action defines the next action to execute
  53506. * @returns The action passed in
  53507. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53508. */
  53509. Action.prototype.then = function (action) {
  53510. this._child = action;
  53511. action._actionManager = this._actionManager;
  53512. action._prepare();
  53513. return action;
  53514. };
  53515. /**
  53516. * Internal only
  53517. * @hidden
  53518. */
  53519. Action.prototype._getProperty = function (propertyPath) {
  53520. return this._actionManager._getProperty(propertyPath);
  53521. };
  53522. /**
  53523. * Internal only
  53524. * @hidden
  53525. */
  53526. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53527. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53528. };
  53529. /**
  53530. * Serialize placeholder for child classes
  53531. * @param parent of child
  53532. * @returns the serialized object
  53533. */
  53534. Action.prototype.serialize = function (parent) {
  53535. };
  53536. /**
  53537. * Internal only called by serialize
  53538. * @hidden
  53539. */
  53540. Action.prototype._serialize = function (serializedAction, parent) {
  53541. var serializationObject = {
  53542. type: 1,
  53543. children: [],
  53544. name: serializedAction.name,
  53545. properties: serializedAction.properties || []
  53546. };
  53547. // Serialize child
  53548. if (this._child) {
  53549. this._child.serialize(serializationObject);
  53550. }
  53551. // Check if "this" has a condition
  53552. if (this._condition) {
  53553. var serializedCondition = this._condition.serialize();
  53554. serializedCondition.children.push(serializationObject);
  53555. if (parent) {
  53556. parent.children.push(serializedCondition);
  53557. }
  53558. return serializedCondition;
  53559. }
  53560. if (parent) {
  53561. parent.children.push(serializationObject);
  53562. }
  53563. return serializationObject;
  53564. };
  53565. /**
  53566. * Internal only
  53567. * @hidden
  53568. */
  53569. Action._SerializeValueAsString = function (value) {
  53570. if (typeof value === "number") {
  53571. return value.toString();
  53572. }
  53573. if (typeof value === "boolean") {
  53574. return value ? "true" : "false";
  53575. }
  53576. if (value instanceof BABYLON.Vector2) {
  53577. return value.x + ", " + value.y;
  53578. }
  53579. if (value instanceof BABYLON.Vector3) {
  53580. return value.x + ", " + value.y + ", " + value.z;
  53581. }
  53582. if (value instanceof BABYLON.Color3) {
  53583. return value.r + ", " + value.g + ", " + value.b;
  53584. }
  53585. if (value instanceof BABYLON.Color4) {
  53586. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53587. }
  53588. return value; // string
  53589. };
  53590. /**
  53591. * Internal only
  53592. * @hidden
  53593. */
  53594. Action._GetTargetProperty = function (target) {
  53595. return {
  53596. name: "target",
  53597. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53598. : target instanceof BABYLON.Light ? "LightProperties"
  53599. : target instanceof BABYLON.Camera ? "CameraProperties"
  53600. : "SceneProperties",
  53601. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53602. };
  53603. };
  53604. return Action;
  53605. }());
  53606. BABYLON.Action = Action;
  53607. })(BABYLON || (BABYLON = {}));
  53608. //# sourceMappingURL=babylon.action.js.map
  53609. var BABYLON;
  53610. (function (BABYLON) {
  53611. /**
  53612. * ActionEvent is the event being sent when an action is triggered.
  53613. */
  53614. var ActionEvent = /** @class */ (function () {
  53615. /**
  53616. * Creates a new ActionEvent
  53617. * @param source The mesh or sprite that triggered the action
  53618. * @param pointerX The X mouse cursor position at the time of the event
  53619. * @param pointerY The Y mouse cursor position at the time of the event
  53620. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53621. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53622. * @param additionalData additional data for the event
  53623. */
  53624. function ActionEvent(
  53625. /** The mesh or sprite that triggered the action */
  53626. source,
  53627. /** The X mouse cursor position at the time of the event */
  53628. pointerX,
  53629. /** The Y mouse cursor position at the time of the event */
  53630. pointerY,
  53631. /** The mesh that is currently pointed at (can be null) */
  53632. meshUnderPointer,
  53633. /** the original (browser) event that triggered the ActionEvent */
  53634. sourceEvent,
  53635. /** additional data for the event */
  53636. additionalData) {
  53637. this.source = source;
  53638. this.pointerX = pointerX;
  53639. this.pointerY = pointerY;
  53640. this.meshUnderPointer = meshUnderPointer;
  53641. this.sourceEvent = sourceEvent;
  53642. this.additionalData = additionalData;
  53643. }
  53644. /**
  53645. * Helper function to auto-create an ActionEvent from a source mesh.
  53646. * @param source The source mesh that triggered the event
  53647. * @param evt The original (browser) event
  53648. * @param additionalData additional data for the event
  53649. * @returns the new ActionEvent
  53650. */
  53651. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53652. var scene = source.getScene();
  53653. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53654. };
  53655. /**
  53656. * Helper function to auto-create an ActionEvent from a source sprite
  53657. * @param source The source sprite that triggered the event
  53658. * @param scene Scene associated with the sprite
  53659. * @param evt The original (browser) event
  53660. * @param additionalData additional data for the event
  53661. * @returns the new ActionEvent
  53662. */
  53663. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53664. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53665. };
  53666. /**
  53667. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53668. * @param scene the scene where the event occurred
  53669. * @param evt The original (browser) event
  53670. * @returns the new ActionEvent
  53671. */
  53672. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53673. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53674. };
  53675. /**
  53676. * Helper function to auto-create an ActionEvent from a primitive
  53677. * @param prim defines the target primitive
  53678. * @param pointerPos defines the pointer position
  53679. * @param evt The original (browser) event
  53680. * @param additionalData additional data for the event
  53681. * @returns the new ActionEvent
  53682. */
  53683. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53684. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53685. };
  53686. return ActionEvent;
  53687. }());
  53688. BABYLON.ActionEvent = ActionEvent;
  53689. /**
  53690. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53691. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53692. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53693. */
  53694. var ActionManager = /** @class */ (function () {
  53695. /**
  53696. * Creates a new action manager
  53697. * @param scene defines the hosting scene
  53698. */
  53699. function ActionManager(scene) {
  53700. // Members
  53701. /** Gets the list of actions */
  53702. this.actions = new Array();
  53703. /** Gets the cursor to use when hovering items */
  53704. this.hoverCursor = '';
  53705. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53706. scene.actionManagers.push(this);
  53707. }
  53708. // Methods
  53709. /**
  53710. * Releases all associated resources
  53711. */
  53712. ActionManager.prototype.dispose = function () {
  53713. var index = this._scene.actionManagers.indexOf(this);
  53714. for (var i = 0; i < this.actions.length; i++) {
  53715. var action = this.actions[i];
  53716. ActionManager.Triggers[action.trigger]--;
  53717. if (ActionManager.Triggers[action.trigger] === 0) {
  53718. delete ActionManager.Triggers[action.trigger];
  53719. }
  53720. }
  53721. if (index > -1) {
  53722. this._scene.actionManagers.splice(index, 1);
  53723. }
  53724. };
  53725. /**
  53726. * Gets hosting scene
  53727. * @returns the hosting scene
  53728. */
  53729. ActionManager.prototype.getScene = function () {
  53730. return this._scene;
  53731. };
  53732. /**
  53733. * Does this action manager handles actions of any of the given triggers
  53734. * @param triggers defines the triggers to be tested
  53735. * @return a boolean indicating whether one (or more) of the triggers is handled
  53736. */
  53737. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53738. for (var index = 0; index < this.actions.length; index++) {
  53739. var action = this.actions[index];
  53740. if (triggers.indexOf(action.trigger) > -1) {
  53741. return true;
  53742. }
  53743. }
  53744. return false;
  53745. };
  53746. /**
  53747. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53748. * speed.
  53749. * @param triggerA defines the trigger to be tested
  53750. * @param triggerB defines the trigger to be tested
  53751. * @return a boolean indicating whether one (or more) of the triggers is handled
  53752. */
  53753. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53754. for (var index = 0; index < this.actions.length; index++) {
  53755. var action = this.actions[index];
  53756. if (triggerA == action.trigger || triggerB == action.trigger) {
  53757. return true;
  53758. }
  53759. }
  53760. return false;
  53761. };
  53762. /**
  53763. * Does this action manager handles actions of a given trigger
  53764. * @param trigger defines the trigger to be tested
  53765. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53766. * @return whether the trigger is handled
  53767. */
  53768. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53769. for (var index = 0; index < this.actions.length; index++) {
  53770. var action = this.actions[index];
  53771. if (action.trigger === trigger) {
  53772. if (parameterPredicate) {
  53773. if (parameterPredicate(action.getTriggerParameter())) {
  53774. return true;
  53775. }
  53776. }
  53777. else {
  53778. return true;
  53779. }
  53780. }
  53781. }
  53782. return false;
  53783. };
  53784. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53785. /**
  53786. * Does this action manager has pointer triggers
  53787. */
  53788. get: function () {
  53789. for (var index = 0; index < this.actions.length; index++) {
  53790. var action = this.actions[index];
  53791. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53792. return true;
  53793. }
  53794. }
  53795. return false;
  53796. },
  53797. enumerable: true,
  53798. configurable: true
  53799. });
  53800. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53801. /**
  53802. * Does this action manager has pick triggers
  53803. */
  53804. get: function () {
  53805. for (var index = 0; index < this.actions.length; index++) {
  53806. var action = this.actions[index];
  53807. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53808. return true;
  53809. }
  53810. }
  53811. return false;
  53812. },
  53813. enumerable: true,
  53814. configurable: true
  53815. });
  53816. Object.defineProperty(ActionManager, "HasTriggers", {
  53817. /**
  53818. * Does exist one action manager with at least one trigger
  53819. **/
  53820. get: function () {
  53821. for (var t in ActionManager.Triggers) {
  53822. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53823. return true;
  53824. }
  53825. }
  53826. return false;
  53827. },
  53828. enumerable: true,
  53829. configurable: true
  53830. });
  53831. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53832. /**
  53833. * Does exist one action manager with at least one pick trigger
  53834. **/
  53835. get: function () {
  53836. for (var t in ActionManager.Triggers) {
  53837. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53838. var t_int = parseInt(t);
  53839. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53840. return true;
  53841. }
  53842. }
  53843. }
  53844. return false;
  53845. },
  53846. enumerable: true,
  53847. configurable: true
  53848. });
  53849. /**
  53850. * Does exist one action manager that handles actions of a given trigger
  53851. * @param trigger defines the trigger to be tested
  53852. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53853. **/
  53854. ActionManager.HasSpecificTrigger = function (trigger) {
  53855. for (var t in ActionManager.Triggers) {
  53856. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53857. var t_int = parseInt(t);
  53858. if (t_int === trigger) {
  53859. return true;
  53860. }
  53861. }
  53862. }
  53863. return false;
  53864. };
  53865. /**
  53866. * Registers an action to this action manager
  53867. * @param action defines the action to be registered
  53868. * @return the action amended (prepared) after registration
  53869. */
  53870. ActionManager.prototype.registerAction = function (action) {
  53871. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53872. if (this.getScene().actionManager !== this) {
  53873. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53874. return null;
  53875. }
  53876. }
  53877. this.actions.push(action);
  53878. if (ActionManager.Triggers[action.trigger]) {
  53879. ActionManager.Triggers[action.trigger]++;
  53880. }
  53881. else {
  53882. ActionManager.Triggers[action.trigger] = 1;
  53883. }
  53884. action._actionManager = this;
  53885. action._prepare();
  53886. return action;
  53887. };
  53888. /**
  53889. * Unregisters an action to this action manager
  53890. * @param action defines the action to be unregistered
  53891. * @return a boolean indicating whether the action has been unregistered
  53892. */
  53893. ActionManager.prototype.unregisterAction = function (action) {
  53894. var index = this.actions.indexOf(action);
  53895. if (index !== -1) {
  53896. this.actions.splice(index, 1);
  53897. ActionManager.Triggers[action.trigger] -= 1;
  53898. if (ActionManager.Triggers[action.trigger] === 0) {
  53899. delete ActionManager.Triggers[action.trigger];
  53900. }
  53901. delete action._actionManager;
  53902. return true;
  53903. }
  53904. return false;
  53905. };
  53906. /**
  53907. * Process a specific trigger
  53908. * @param trigger defines the trigger to process
  53909. * @param evt defines the event details to be processed
  53910. */
  53911. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53912. for (var index = 0; index < this.actions.length; index++) {
  53913. var action = this.actions[index];
  53914. if (action.trigger === trigger) {
  53915. if (evt) {
  53916. if (trigger === ActionManager.OnKeyUpTrigger
  53917. || trigger === ActionManager.OnKeyDownTrigger) {
  53918. var parameter = action.getTriggerParameter();
  53919. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53920. if (!parameter.toLowerCase) {
  53921. continue;
  53922. }
  53923. var lowerCase = parameter.toLowerCase();
  53924. if (lowerCase !== evt.sourceEvent.key) {
  53925. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53926. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53927. if (actualkey !== lowerCase) {
  53928. continue;
  53929. }
  53930. }
  53931. }
  53932. }
  53933. }
  53934. action._executeCurrent(evt);
  53935. }
  53936. }
  53937. };
  53938. /** @hidden */
  53939. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53940. var properties = propertyPath.split(".");
  53941. for (var index = 0; index < properties.length - 1; index++) {
  53942. target = target[properties[index]];
  53943. }
  53944. return target;
  53945. };
  53946. /** @hidden */
  53947. ActionManager.prototype._getProperty = function (propertyPath) {
  53948. var properties = propertyPath.split(".");
  53949. return properties[properties.length - 1];
  53950. };
  53951. /**
  53952. * Serialize this manager to a JSON object
  53953. * @param name defines the property name to store this manager
  53954. * @returns a JSON representation of this manager
  53955. */
  53956. ActionManager.prototype.serialize = function (name) {
  53957. var root = {
  53958. children: new Array(),
  53959. name: name,
  53960. type: 3,
  53961. properties: new Array() // Empty for root but required
  53962. };
  53963. for (var i = 0; i < this.actions.length; i++) {
  53964. var triggerObject = {
  53965. type: 0,
  53966. children: new Array(),
  53967. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53968. properties: new Array()
  53969. };
  53970. var triggerOptions = this.actions[i].triggerOptions;
  53971. if (triggerOptions && typeof triggerOptions !== "number") {
  53972. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53973. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53974. }
  53975. else {
  53976. var parameter = {};
  53977. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53978. if (triggerOptions.parameter.mesh) {
  53979. parameter._meshId = triggerOptions.parameter.mesh.id;
  53980. }
  53981. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53982. }
  53983. }
  53984. // Serialize child action, recursively
  53985. this.actions[i].serialize(triggerObject);
  53986. // Add serialized trigger
  53987. root.children.push(triggerObject);
  53988. }
  53989. return root;
  53990. };
  53991. /**
  53992. * Creates a new ActionManager from a JSON data
  53993. * @param parsedActions defines the JSON data to read from
  53994. * @param object defines the hosting mesh
  53995. * @param scene defines the hosting scene
  53996. */
  53997. ActionManager.Parse = function (parsedActions, object, scene) {
  53998. var actionManager = new ActionManager(scene);
  53999. if (object === null)
  54000. scene.actionManager = actionManager;
  54001. else
  54002. object.actionManager = actionManager;
  54003. // instanciate a new object
  54004. var instanciate = function (name, params) {
  54005. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54006. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54007. newInstance.constructor.apply(newInstance, params);
  54008. return newInstance;
  54009. };
  54010. var parseParameter = function (name, value, target, propertyPath) {
  54011. if (propertyPath === null) {
  54012. // String, boolean or float
  54013. var floatValue = parseFloat(value);
  54014. if (value === "true" || value === "false")
  54015. return value === "true";
  54016. else
  54017. return isNaN(floatValue) ? value : floatValue;
  54018. }
  54019. var effectiveTarget = propertyPath.split(".");
  54020. var values = value.split(",");
  54021. // Get effective Target
  54022. for (var i = 0; i < effectiveTarget.length; i++) {
  54023. target = target[effectiveTarget[i]];
  54024. }
  54025. // Return appropriate value with its type
  54026. if (typeof (target) === "boolean")
  54027. return values[0] === "true";
  54028. if (typeof (target) === "string")
  54029. return values[0];
  54030. // Parameters with multiple values such as Vector3 etc.
  54031. var split = new Array();
  54032. for (var i = 0; i < values.length; i++)
  54033. split.push(parseFloat(values[i]));
  54034. if (target instanceof BABYLON.Vector3)
  54035. return BABYLON.Vector3.FromArray(split);
  54036. if (target instanceof BABYLON.Vector4)
  54037. return BABYLON.Vector4.FromArray(split);
  54038. if (target instanceof BABYLON.Color3)
  54039. return BABYLON.Color3.FromArray(split);
  54040. if (target instanceof BABYLON.Color4)
  54041. return BABYLON.Color4.FromArray(split);
  54042. return parseFloat(values[0]);
  54043. };
  54044. // traverse graph per trigger
  54045. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54046. if (combineArray === void 0) { combineArray = null; }
  54047. if (parsedAction.detached)
  54048. return;
  54049. var parameters = new Array();
  54050. var target = null;
  54051. var propertyPath = null;
  54052. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54053. // Parameters
  54054. if (parsedAction.type === 2)
  54055. parameters.push(actionManager);
  54056. else
  54057. parameters.push(trigger);
  54058. if (combine) {
  54059. var actions = new Array();
  54060. for (var j = 0; j < parsedAction.combine.length; j++) {
  54061. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54062. }
  54063. parameters.push(actions);
  54064. }
  54065. else {
  54066. for (var i = 0; i < parsedAction.properties.length; i++) {
  54067. var value = parsedAction.properties[i].value;
  54068. var name = parsedAction.properties[i].name;
  54069. var targetType = parsedAction.properties[i].targetType;
  54070. if (name === "target")
  54071. if (targetType !== null && targetType === "SceneProperties")
  54072. value = target = scene;
  54073. else
  54074. value = target = scene.getNodeByName(value);
  54075. else if (name === "parent")
  54076. value = scene.getNodeByName(value);
  54077. else if (name === "sound") {
  54078. // Can not externalize to component, so only checks for the presence off the API.
  54079. if (scene.getSoundByName) {
  54080. value = scene.getSoundByName(value);
  54081. }
  54082. }
  54083. else if (name !== "propertyPath") {
  54084. if (parsedAction.type === 2 && name === "operator")
  54085. value = BABYLON.ValueCondition[value];
  54086. else
  54087. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54088. }
  54089. else {
  54090. propertyPath = value;
  54091. }
  54092. parameters.push(value);
  54093. }
  54094. }
  54095. if (combineArray === null) {
  54096. parameters.push(condition);
  54097. }
  54098. else {
  54099. parameters.push(null);
  54100. }
  54101. // If interpolate value action
  54102. if (parsedAction.name === "InterpolateValueAction") {
  54103. var param = parameters[parameters.length - 2];
  54104. parameters[parameters.length - 1] = param;
  54105. parameters[parameters.length - 2] = condition;
  54106. }
  54107. // Action or condition(s) and not CombineAction
  54108. var newAction = instanciate(parsedAction.name, parameters);
  54109. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54110. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54111. if (action)
  54112. action.then(nothing);
  54113. else
  54114. actionManager.registerAction(nothing);
  54115. action = nothing;
  54116. }
  54117. if (combineArray === null) {
  54118. if (newAction instanceof BABYLON.Condition) {
  54119. condition = newAction;
  54120. newAction = action;
  54121. }
  54122. else {
  54123. condition = null;
  54124. if (action)
  54125. action.then(newAction);
  54126. else
  54127. actionManager.registerAction(newAction);
  54128. }
  54129. }
  54130. else {
  54131. combineArray.push(newAction);
  54132. }
  54133. for (var i = 0; i < parsedAction.children.length; i++)
  54134. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54135. };
  54136. // triggers
  54137. for (var i = 0; i < parsedActions.children.length; i++) {
  54138. var triggerParams;
  54139. var trigger = parsedActions.children[i];
  54140. if (trigger.properties.length > 0) {
  54141. var param = trigger.properties[0].value;
  54142. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54143. if (value._meshId) {
  54144. value.mesh = scene.getMeshByID(value._meshId);
  54145. }
  54146. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54147. }
  54148. else
  54149. triggerParams = ActionManager[trigger.name];
  54150. for (var j = 0; j < trigger.children.length; j++) {
  54151. if (!trigger.detached)
  54152. traverse(trigger.children[j], triggerParams, null, null);
  54153. }
  54154. }
  54155. };
  54156. /**
  54157. * Get a trigger name by index
  54158. * @param trigger defines the trigger index
  54159. * @returns a trigger name
  54160. */
  54161. ActionManager.GetTriggerName = function (trigger) {
  54162. switch (trigger) {
  54163. case 0: return "NothingTrigger";
  54164. case 1: return "OnPickTrigger";
  54165. case 2: return "OnLeftPickTrigger";
  54166. case 3: return "OnRightPickTrigger";
  54167. case 4: return "OnCenterPickTrigger";
  54168. case 5: return "OnPickDownTrigger";
  54169. case 6: return "OnPickUpTrigger";
  54170. case 7: return "OnLongPressTrigger";
  54171. case 8: return "OnPointerOverTrigger";
  54172. case 9: return "OnPointerOutTrigger";
  54173. case 10: return "OnEveryFrameTrigger";
  54174. case 11: return "OnIntersectionEnterTrigger";
  54175. case 12: return "OnIntersectionExitTrigger";
  54176. case 13: return "OnKeyDownTrigger";
  54177. case 14: return "OnKeyUpTrigger";
  54178. case 15: return "OnPickOutTrigger";
  54179. default: return "";
  54180. }
  54181. };
  54182. /**
  54183. * Nothing
  54184. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54185. */
  54186. ActionManager.NothingTrigger = 0;
  54187. /**
  54188. * On pick
  54189. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54190. */
  54191. ActionManager.OnPickTrigger = 1;
  54192. /**
  54193. * On left pick
  54194. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54195. */
  54196. ActionManager.OnLeftPickTrigger = 2;
  54197. /**
  54198. * On right pick
  54199. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54200. */
  54201. ActionManager.OnRightPickTrigger = 3;
  54202. /**
  54203. * On center pick
  54204. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54205. */
  54206. ActionManager.OnCenterPickTrigger = 4;
  54207. /**
  54208. * On pick down
  54209. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54210. */
  54211. ActionManager.OnPickDownTrigger = 5;
  54212. /**
  54213. * On double pick
  54214. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54215. */
  54216. ActionManager.OnDoublePickTrigger = 6;
  54217. /**
  54218. * On pick up
  54219. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54220. */
  54221. ActionManager.OnPickUpTrigger = 7;
  54222. /**
  54223. * On pick out.
  54224. * This trigger will only be raised if you also declared a OnPickDown
  54225. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54226. */
  54227. ActionManager.OnPickOutTrigger = 16;
  54228. /**
  54229. * On long press
  54230. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54231. */
  54232. ActionManager.OnLongPressTrigger = 8;
  54233. /**
  54234. * On pointer over
  54235. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54236. */
  54237. ActionManager.OnPointerOverTrigger = 9;
  54238. /**
  54239. * On pointer out
  54240. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54241. */
  54242. ActionManager.OnPointerOutTrigger = 10;
  54243. /**
  54244. * On every frame
  54245. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54246. */
  54247. ActionManager.OnEveryFrameTrigger = 11;
  54248. /**
  54249. * On intersection enter
  54250. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54251. */
  54252. ActionManager.OnIntersectionEnterTrigger = 12;
  54253. /**
  54254. * On intersection exit
  54255. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54256. */
  54257. ActionManager.OnIntersectionExitTrigger = 13;
  54258. /**
  54259. * On key down
  54260. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54261. */
  54262. ActionManager.OnKeyDownTrigger = 14;
  54263. /**
  54264. * On key up
  54265. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54266. */
  54267. ActionManager.OnKeyUpTrigger = 15;
  54268. /** Gets the list of active triggers */
  54269. ActionManager.Triggers = {};
  54270. return ActionManager;
  54271. }());
  54272. BABYLON.ActionManager = ActionManager;
  54273. })(BABYLON || (BABYLON = {}));
  54274. //# sourceMappingURL=babylon.actionManager.js.map
  54275. var BABYLON;
  54276. (function (BABYLON) {
  54277. /**
  54278. * This defines an action responsible to change the value of a property
  54279. * by interpolating between its current value and the newly set one once triggered.
  54280. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54281. */
  54282. var InterpolateValueAction = /** @class */ (function (_super) {
  54283. __extends(InterpolateValueAction, _super);
  54284. /**
  54285. * Instantiate the action
  54286. * @param triggerOptions defines the trigger options
  54287. * @param target defines the object containing the value to interpolate
  54288. * @param propertyPath defines the path to the property in the target object
  54289. * @param value defines the target value at the end of the interpolation
  54290. * @param duration deines the time it will take for the property to interpolate to the value.
  54291. * @param condition defines the trigger related conditions
  54292. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54293. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54294. */
  54295. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54296. if (duration === void 0) { duration = 1000; }
  54297. var _this = _super.call(this, triggerOptions, condition) || this;
  54298. /**
  54299. * Defines the time it will take for the property to interpolate to the value.
  54300. */
  54301. _this.duration = 1000;
  54302. /**
  54303. * Observable triggered once the interpolation animation has been done.
  54304. */
  54305. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54306. _this.propertyPath = propertyPath;
  54307. _this.value = value;
  54308. _this.duration = duration;
  54309. _this.stopOtherAnimations = stopOtherAnimations;
  54310. _this.onInterpolationDone = onInterpolationDone;
  54311. _this._target = _this._effectiveTarget = target;
  54312. return _this;
  54313. }
  54314. /** @hidden */
  54315. InterpolateValueAction.prototype._prepare = function () {
  54316. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54317. this._property = this._getProperty(this.propertyPath);
  54318. };
  54319. /**
  54320. * Execute the action starts the value interpolation.
  54321. */
  54322. InterpolateValueAction.prototype.execute = function () {
  54323. var _this = this;
  54324. var scene = this._actionManager.getScene();
  54325. var keys = [
  54326. {
  54327. frame: 0,
  54328. value: this._effectiveTarget[this._property]
  54329. }, {
  54330. frame: 100,
  54331. value: this.value
  54332. }
  54333. ];
  54334. var dataType;
  54335. if (typeof this.value === "number") {
  54336. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54337. }
  54338. else if (this.value instanceof BABYLON.Color3) {
  54339. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54340. }
  54341. else if (this.value instanceof BABYLON.Vector3) {
  54342. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54343. }
  54344. else if (this.value instanceof BABYLON.Matrix) {
  54345. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54346. }
  54347. else if (this.value instanceof BABYLON.Quaternion) {
  54348. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54349. }
  54350. else {
  54351. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54352. return;
  54353. }
  54354. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54355. animation.setKeys(keys);
  54356. if (this.stopOtherAnimations) {
  54357. scene.stopAnimation(this._effectiveTarget);
  54358. }
  54359. var wrapper = function () {
  54360. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54361. if (_this.onInterpolationDone) {
  54362. _this.onInterpolationDone();
  54363. }
  54364. };
  54365. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54366. };
  54367. /**
  54368. * Serializes the actions and its related information.
  54369. * @param parent defines the object to serialize in
  54370. * @returns the serialized object
  54371. */
  54372. InterpolateValueAction.prototype.serialize = function (parent) {
  54373. return _super.prototype._serialize.call(this, {
  54374. name: "InterpolateValueAction",
  54375. properties: [
  54376. BABYLON.Action._GetTargetProperty(this._target),
  54377. { name: "propertyPath", value: this.propertyPath },
  54378. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54379. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54380. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54381. ]
  54382. }, parent);
  54383. };
  54384. return InterpolateValueAction;
  54385. }(BABYLON.Action));
  54386. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54387. })(BABYLON || (BABYLON = {}));
  54388. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54389. var BABYLON;
  54390. (function (BABYLON) {
  54391. /**
  54392. * This defines an action responsible to toggle a boolean once triggered.
  54393. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54394. */
  54395. var SwitchBooleanAction = /** @class */ (function (_super) {
  54396. __extends(SwitchBooleanAction, _super);
  54397. /**
  54398. * Instantiate the action
  54399. * @param triggerOptions defines the trigger options
  54400. * @param target defines the object containing the boolean
  54401. * @param propertyPath defines the path to the boolean property in the target object
  54402. * @param condition defines the trigger related conditions
  54403. */
  54404. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54405. var _this = _super.call(this, triggerOptions, condition) || this;
  54406. _this.propertyPath = propertyPath;
  54407. _this._target = _this._effectiveTarget = target;
  54408. return _this;
  54409. }
  54410. /** @hidden */
  54411. SwitchBooleanAction.prototype._prepare = function () {
  54412. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54413. this._property = this._getProperty(this.propertyPath);
  54414. };
  54415. /**
  54416. * Execute the action toggle the boolean value.
  54417. */
  54418. SwitchBooleanAction.prototype.execute = function () {
  54419. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54420. };
  54421. /**
  54422. * Serializes the actions and its related information.
  54423. * @param parent defines the object to serialize in
  54424. * @returns the serialized object
  54425. */
  54426. SwitchBooleanAction.prototype.serialize = function (parent) {
  54427. return _super.prototype._serialize.call(this, {
  54428. name: "SwitchBooleanAction",
  54429. properties: [
  54430. BABYLON.Action._GetTargetProperty(this._target),
  54431. { name: "propertyPath", value: this.propertyPath }
  54432. ]
  54433. }, parent);
  54434. };
  54435. return SwitchBooleanAction;
  54436. }(BABYLON.Action));
  54437. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54438. /**
  54439. * This defines an action responsible to set a the state field of the target
  54440. * to a desired value once triggered.
  54441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54442. */
  54443. var SetStateAction = /** @class */ (function (_super) {
  54444. __extends(SetStateAction, _super);
  54445. /**
  54446. * Instantiate the action
  54447. * @param triggerOptions defines the trigger options
  54448. * @param target defines the object containing the state property
  54449. * @param value defines the value to store in the state field
  54450. * @param condition defines the trigger related conditions
  54451. */
  54452. function SetStateAction(triggerOptions, target, value, condition) {
  54453. var _this = _super.call(this, triggerOptions, condition) || this;
  54454. _this.value = value;
  54455. _this._target = target;
  54456. return _this;
  54457. }
  54458. /**
  54459. * Execute the action and store the value on the target state property.
  54460. */
  54461. SetStateAction.prototype.execute = function () {
  54462. this._target.state = this.value;
  54463. };
  54464. /**
  54465. * Serializes the actions and its related information.
  54466. * @param parent defines the object to serialize in
  54467. * @returns the serialized object
  54468. */
  54469. SetStateAction.prototype.serialize = function (parent) {
  54470. return _super.prototype._serialize.call(this, {
  54471. name: "SetStateAction",
  54472. properties: [
  54473. BABYLON.Action._GetTargetProperty(this._target),
  54474. { name: "value", value: this.value }
  54475. ]
  54476. }, parent);
  54477. };
  54478. return SetStateAction;
  54479. }(BABYLON.Action));
  54480. BABYLON.SetStateAction = SetStateAction;
  54481. /**
  54482. * This defines an action responsible to set a property of the target
  54483. * to a desired value once triggered.
  54484. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54485. */
  54486. var SetValueAction = /** @class */ (function (_super) {
  54487. __extends(SetValueAction, _super);
  54488. /**
  54489. * Instantiate the action
  54490. * @param triggerOptions defines the trigger options
  54491. * @param target defines the object containing the property
  54492. * @param propertyPath defines the path of the property to set in the target
  54493. * @param value defines the value to set in the property
  54494. * @param condition defines the trigger related conditions
  54495. */
  54496. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54497. var _this = _super.call(this, triggerOptions, condition) || this;
  54498. _this.propertyPath = propertyPath;
  54499. _this.value = value;
  54500. _this._target = _this._effectiveTarget = target;
  54501. return _this;
  54502. }
  54503. /** @hidden */
  54504. SetValueAction.prototype._prepare = function () {
  54505. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54506. this._property = this._getProperty(this.propertyPath);
  54507. };
  54508. /**
  54509. * Execute the action and set the targetted property to the desired value.
  54510. */
  54511. SetValueAction.prototype.execute = function () {
  54512. this._effectiveTarget[this._property] = this.value;
  54513. if (this._target.markAsDirty) {
  54514. this._target.markAsDirty(this._property);
  54515. }
  54516. };
  54517. /**
  54518. * Serializes the actions and its related information.
  54519. * @param parent defines the object to serialize in
  54520. * @returns the serialized object
  54521. */
  54522. SetValueAction.prototype.serialize = function (parent) {
  54523. return _super.prototype._serialize.call(this, {
  54524. name: "SetValueAction",
  54525. properties: [
  54526. BABYLON.Action._GetTargetProperty(this._target),
  54527. { name: "propertyPath", value: this.propertyPath },
  54528. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54529. ]
  54530. }, parent);
  54531. };
  54532. return SetValueAction;
  54533. }(BABYLON.Action));
  54534. BABYLON.SetValueAction = SetValueAction;
  54535. /**
  54536. * This defines an action responsible to increment the target value
  54537. * to a desired value once triggered.
  54538. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54539. */
  54540. var IncrementValueAction = /** @class */ (function (_super) {
  54541. __extends(IncrementValueAction, _super);
  54542. /**
  54543. * Instantiate the action
  54544. * @param triggerOptions defines the trigger options
  54545. * @param target defines the object containing the property
  54546. * @param propertyPath defines the path of the property to increment in the target
  54547. * @param value defines the value value we should increment the property by
  54548. * @param condition defines the trigger related conditions
  54549. */
  54550. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54551. var _this = _super.call(this, triggerOptions, condition) || this;
  54552. _this.propertyPath = propertyPath;
  54553. _this.value = value;
  54554. _this._target = _this._effectiveTarget = target;
  54555. return _this;
  54556. }
  54557. /** @hidden */
  54558. IncrementValueAction.prototype._prepare = function () {
  54559. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54560. this._property = this._getProperty(this.propertyPath);
  54561. if (typeof this._effectiveTarget[this._property] !== "number") {
  54562. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54563. }
  54564. };
  54565. /**
  54566. * Execute the action and increment the target of the value amount.
  54567. */
  54568. IncrementValueAction.prototype.execute = function () {
  54569. this._effectiveTarget[this._property] += this.value;
  54570. if (this._target.markAsDirty) {
  54571. this._target.markAsDirty(this._property);
  54572. }
  54573. };
  54574. /**
  54575. * Serializes the actions and its related information.
  54576. * @param parent defines the object to serialize in
  54577. * @returns the serialized object
  54578. */
  54579. IncrementValueAction.prototype.serialize = function (parent) {
  54580. return _super.prototype._serialize.call(this, {
  54581. name: "IncrementValueAction",
  54582. properties: [
  54583. BABYLON.Action._GetTargetProperty(this._target),
  54584. { name: "propertyPath", value: this.propertyPath },
  54585. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54586. ]
  54587. }, parent);
  54588. };
  54589. return IncrementValueAction;
  54590. }(BABYLON.Action));
  54591. BABYLON.IncrementValueAction = IncrementValueAction;
  54592. /**
  54593. * This defines an action responsible to start an animation once triggered.
  54594. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54595. */
  54596. var PlayAnimationAction = /** @class */ (function (_super) {
  54597. __extends(PlayAnimationAction, _super);
  54598. /**
  54599. * Instantiate the action
  54600. * @param triggerOptions defines the trigger options
  54601. * @param target defines the target animation or animation name
  54602. * @param from defines from where the animation should start (animation frame)
  54603. * @param end defines where the animation should stop (animation frame)
  54604. * @param loop defines if the animation should loop or stop after the first play
  54605. * @param condition defines the trigger related conditions
  54606. */
  54607. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54608. var _this = _super.call(this, triggerOptions, condition) || this;
  54609. _this.from = from;
  54610. _this.to = to;
  54611. _this.loop = loop;
  54612. _this._target = target;
  54613. return _this;
  54614. }
  54615. /** @hidden */
  54616. PlayAnimationAction.prototype._prepare = function () {
  54617. };
  54618. /**
  54619. * Execute the action and play the animation.
  54620. */
  54621. PlayAnimationAction.prototype.execute = function () {
  54622. var scene = this._actionManager.getScene();
  54623. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54624. };
  54625. /**
  54626. * Serializes the actions and its related information.
  54627. * @param parent defines the object to serialize in
  54628. * @returns the serialized object
  54629. */
  54630. PlayAnimationAction.prototype.serialize = function (parent) {
  54631. return _super.prototype._serialize.call(this, {
  54632. name: "PlayAnimationAction",
  54633. properties: [
  54634. BABYLON.Action._GetTargetProperty(this._target),
  54635. { name: "from", value: String(this.from) },
  54636. { name: "to", value: String(this.to) },
  54637. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54638. ]
  54639. }, parent);
  54640. };
  54641. return PlayAnimationAction;
  54642. }(BABYLON.Action));
  54643. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54644. /**
  54645. * This defines an action responsible to stop an animation once triggered.
  54646. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54647. */
  54648. var StopAnimationAction = /** @class */ (function (_super) {
  54649. __extends(StopAnimationAction, _super);
  54650. /**
  54651. * Instantiate the action
  54652. * @param triggerOptions defines the trigger options
  54653. * @param target defines the target animation or animation name
  54654. * @param condition defines the trigger related conditions
  54655. */
  54656. function StopAnimationAction(triggerOptions, target, condition) {
  54657. var _this = _super.call(this, triggerOptions, condition) || this;
  54658. _this._target = target;
  54659. return _this;
  54660. }
  54661. /** @hidden */
  54662. StopAnimationAction.prototype._prepare = function () {
  54663. };
  54664. /**
  54665. * Execute the action and stop the animation.
  54666. */
  54667. StopAnimationAction.prototype.execute = function () {
  54668. var scene = this._actionManager.getScene();
  54669. scene.stopAnimation(this._target);
  54670. };
  54671. /**
  54672. * Serializes the actions and its related information.
  54673. * @param parent defines the object to serialize in
  54674. * @returns the serialized object
  54675. */
  54676. StopAnimationAction.prototype.serialize = function (parent) {
  54677. return _super.prototype._serialize.call(this, {
  54678. name: "StopAnimationAction",
  54679. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54680. }, parent);
  54681. };
  54682. return StopAnimationAction;
  54683. }(BABYLON.Action));
  54684. BABYLON.StopAnimationAction = StopAnimationAction;
  54685. /**
  54686. * This defines an action responsible that does nothing once triggered.
  54687. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54688. */
  54689. var DoNothingAction = /** @class */ (function (_super) {
  54690. __extends(DoNothingAction, _super);
  54691. /**
  54692. * Instantiate the action
  54693. * @param triggerOptions defines the trigger options
  54694. * @param condition defines the trigger related conditions
  54695. */
  54696. function DoNothingAction(triggerOptions, condition) {
  54697. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54698. return _super.call(this, triggerOptions, condition) || this;
  54699. }
  54700. /**
  54701. * Execute the action and do nothing.
  54702. */
  54703. DoNothingAction.prototype.execute = function () {
  54704. };
  54705. /**
  54706. * Serializes the actions and its related information.
  54707. * @param parent defines the object to serialize in
  54708. * @returns the serialized object
  54709. */
  54710. DoNothingAction.prototype.serialize = function (parent) {
  54711. return _super.prototype._serialize.call(this, {
  54712. name: "DoNothingAction",
  54713. properties: []
  54714. }, parent);
  54715. };
  54716. return DoNothingAction;
  54717. }(BABYLON.Action));
  54718. BABYLON.DoNothingAction = DoNothingAction;
  54719. /**
  54720. * This defines an action responsible to trigger several actions once triggered.
  54721. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54722. */
  54723. var CombineAction = /** @class */ (function (_super) {
  54724. __extends(CombineAction, _super);
  54725. /**
  54726. * Instantiate the action
  54727. * @param triggerOptions defines the trigger options
  54728. * @param children defines the list of aggregated animations to run
  54729. * @param condition defines the trigger related conditions
  54730. */
  54731. function CombineAction(triggerOptions, children, condition) {
  54732. var _this = _super.call(this, triggerOptions, condition) || this;
  54733. _this.children = children;
  54734. return _this;
  54735. }
  54736. /** @hidden */
  54737. CombineAction.prototype._prepare = function () {
  54738. for (var index = 0; index < this.children.length; index++) {
  54739. this.children[index]._actionManager = this._actionManager;
  54740. this.children[index]._prepare();
  54741. }
  54742. };
  54743. /**
  54744. * Execute the action and executes all the aggregated actions.
  54745. */
  54746. CombineAction.prototype.execute = function (evt) {
  54747. for (var index = 0; index < this.children.length; index++) {
  54748. this.children[index].execute(evt);
  54749. }
  54750. };
  54751. /**
  54752. * Serializes the actions and its related information.
  54753. * @param parent defines the object to serialize in
  54754. * @returns the serialized object
  54755. */
  54756. CombineAction.prototype.serialize = function (parent) {
  54757. var serializationObject = _super.prototype._serialize.call(this, {
  54758. name: "CombineAction",
  54759. properties: [],
  54760. combine: []
  54761. }, parent);
  54762. for (var i = 0; i < this.children.length; i++) {
  54763. serializationObject.combine.push(this.children[i].serialize(null));
  54764. }
  54765. return serializationObject;
  54766. };
  54767. return CombineAction;
  54768. }(BABYLON.Action));
  54769. BABYLON.CombineAction = CombineAction;
  54770. /**
  54771. * This defines an action responsible to run code (external event) once triggered.
  54772. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54773. */
  54774. var ExecuteCodeAction = /** @class */ (function (_super) {
  54775. __extends(ExecuteCodeAction, _super);
  54776. /**
  54777. * Instantiate the action
  54778. * @param triggerOptions defines the trigger options
  54779. * @param func defines the callback function to run
  54780. * @param condition defines the trigger related conditions
  54781. */
  54782. function ExecuteCodeAction(triggerOptions, func, condition) {
  54783. var _this = _super.call(this, triggerOptions, condition) || this;
  54784. _this.func = func;
  54785. return _this;
  54786. }
  54787. /**
  54788. * Execute the action and run the attached code.
  54789. */
  54790. ExecuteCodeAction.prototype.execute = function (evt) {
  54791. this.func(evt);
  54792. };
  54793. return ExecuteCodeAction;
  54794. }(BABYLON.Action));
  54795. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54796. /**
  54797. * This defines an action responsible to set the parent property of the target once triggered.
  54798. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54799. */
  54800. var SetParentAction = /** @class */ (function (_super) {
  54801. __extends(SetParentAction, _super);
  54802. /**
  54803. * Instantiate the action
  54804. * @param triggerOptions defines the trigger options
  54805. * @param target defines the target containing the parent property
  54806. * @param parent defines from where the animation should start (animation frame)
  54807. * @param condition defines the trigger related conditions
  54808. */
  54809. function SetParentAction(triggerOptions, target, parent, condition) {
  54810. var _this = _super.call(this, triggerOptions, condition) || this;
  54811. _this._target = target;
  54812. _this._parent = parent;
  54813. return _this;
  54814. }
  54815. /** @hidden */
  54816. SetParentAction.prototype._prepare = function () {
  54817. };
  54818. /**
  54819. * Execute the action and set the parent property.
  54820. */
  54821. SetParentAction.prototype.execute = function () {
  54822. if (this._target.parent === this._parent) {
  54823. return;
  54824. }
  54825. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54826. invertParentWorldMatrix.invert();
  54827. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54828. this._target.parent = this._parent;
  54829. };
  54830. /**
  54831. * Serializes the actions and its related information.
  54832. * @param parent defines the object to serialize in
  54833. * @returns the serialized object
  54834. */
  54835. SetParentAction.prototype.serialize = function (parent) {
  54836. return _super.prototype._serialize.call(this, {
  54837. name: "SetParentAction",
  54838. properties: [
  54839. BABYLON.Action._GetTargetProperty(this._target),
  54840. BABYLON.Action._GetTargetProperty(this._parent),
  54841. ]
  54842. }, parent);
  54843. };
  54844. return SetParentAction;
  54845. }(BABYLON.Action));
  54846. BABYLON.SetParentAction = SetParentAction;
  54847. })(BABYLON || (BABYLON = {}));
  54848. //# sourceMappingURL=babylon.directActions.js.map
  54849. var BABYLON;
  54850. (function (BABYLON) {
  54851. var SpriteManager = /** @class */ (function () {
  54852. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54853. if (epsilon === void 0) { epsilon = 0.01; }
  54854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54855. this.name = name;
  54856. this.sprites = new Array();
  54857. this.renderingGroupId = 0;
  54858. this.layerMask = 0x0FFFFFFF;
  54859. this.fogEnabled = true;
  54860. this.isPickable = false;
  54861. /**
  54862. * An event triggered when the manager is disposed.
  54863. */
  54864. this.onDisposeObservable = new BABYLON.Observable();
  54865. this._vertexBuffers = {};
  54866. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54867. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54868. }
  54869. this._capacity = capacity;
  54870. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54871. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54872. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54873. if (cellSize.width && cellSize.height) {
  54874. this.cellWidth = cellSize.width;
  54875. this.cellHeight = cellSize.height;
  54876. }
  54877. else if (cellSize !== undefined) {
  54878. this.cellWidth = cellSize;
  54879. this.cellHeight = cellSize;
  54880. }
  54881. else {
  54882. return;
  54883. }
  54884. this._epsilon = epsilon;
  54885. this._scene = scene;
  54886. this._scene.spriteManagers.push(this);
  54887. var indices = [];
  54888. var index = 0;
  54889. for (var count = 0; count < capacity; count++) {
  54890. indices.push(index);
  54891. indices.push(index + 1);
  54892. indices.push(index + 2);
  54893. indices.push(index);
  54894. indices.push(index + 2);
  54895. indices.push(index + 3);
  54896. index += 4;
  54897. }
  54898. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54899. // VBO
  54900. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54901. this._vertexData = new Float32Array(capacity * 16 * 4);
  54902. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54903. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54904. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54905. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54906. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54908. this._vertexBuffers["options"] = options;
  54909. this._vertexBuffers["cellInfo"] = cellInfo;
  54910. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54911. // Effects
  54912. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54913. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54914. }
  54915. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54916. set: function (callback) {
  54917. if (this._onDisposeObserver) {
  54918. this.onDisposeObservable.remove(this._onDisposeObserver);
  54919. }
  54920. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54921. },
  54922. enumerable: true,
  54923. configurable: true
  54924. });
  54925. Object.defineProperty(SpriteManager.prototype, "texture", {
  54926. get: function () {
  54927. return this._spriteTexture;
  54928. },
  54929. set: function (value) {
  54930. this._spriteTexture = value;
  54931. },
  54932. enumerable: true,
  54933. configurable: true
  54934. });
  54935. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54936. var arrayOffset = index * 16;
  54937. if (offsetX === 0)
  54938. offsetX = this._epsilon;
  54939. else if (offsetX === 1)
  54940. offsetX = 1 - this._epsilon;
  54941. if (offsetY === 0)
  54942. offsetY = this._epsilon;
  54943. else if (offsetY === 1)
  54944. offsetY = 1 - this._epsilon;
  54945. this._vertexData[arrayOffset] = sprite.position.x;
  54946. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54947. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54948. this._vertexData[arrayOffset + 3] = sprite.angle;
  54949. this._vertexData[arrayOffset + 4] = sprite.width;
  54950. this._vertexData[arrayOffset + 5] = sprite.height;
  54951. this._vertexData[arrayOffset + 6] = offsetX;
  54952. this._vertexData[arrayOffset + 7] = offsetY;
  54953. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54954. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54955. var offset = (sprite.cellIndex / rowSize) >> 0;
  54956. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54957. this._vertexData[arrayOffset + 11] = offset;
  54958. // Color
  54959. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54960. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54961. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54962. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54963. };
  54964. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54965. var count = Math.min(this._capacity, this.sprites.length);
  54966. var min = BABYLON.Vector3.Zero();
  54967. var max = BABYLON.Vector3.Zero();
  54968. var distance = Number.MAX_VALUE;
  54969. var currentSprite = null;
  54970. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54971. var cameraView = camera.getViewMatrix();
  54972. for (var index = 0; index < count; index++) {
  54973. var sprite = this.sprites[index];
  54974. if (!sprite) {
  54975. continue;
  54976. }
  54977. if (predicate) {
  54978. if (!predicate(sprite)) {
  54979. continue;
  54980. }
  54981. }
  54982. else if (!sprite.isPickable) {
  54983. continue;
  54984. }
  54985. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54986. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54987. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54988. if (ray.intersectsBoxMinMax(min, max)) {
  54989. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54990. if (distance > currentDistance) {
  54991. distance = currentDistance;
  54992. currentSprite = sprite;
  54993. if (fastCheck) {
  54994. break;
  54995. }
  54996. }
  54997. }
  54998. }
  54999. if (currentSprite) {
  55000. var result = new BABYLON.PickingInfo();
  55001. result.hit = true;
  55002. result.pickedSprite = currentSprite;
  55003. result.distance = distance;
  55004. return result;
  55005. }
  55006. return null;
  55007. };
  55008. SpriteManager.prototype.render = function () {
  55009. // Check
  55010. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55011. return;
  55012. var engine = this._scene.getEngine();
  55013. var baseSize = this._spriteTexture.getBaseSize();
  55014. // Sprites
  55015. var deltaTime = engine.getDeltaTime();
  55016. var max = Math.min(this._capacity, this.sprites.length);
  55017. var rowSize = baseSize.width / this.cellWidth;
  55018. var offset = 0;
  55019. for (var index = 0; index < max; index++) {
  55020. var sprite = this.sprites[index];
  55021. if (!sprite || !sprite.isVisible) {
  55022. continue;
  55023. }
  55024. sprite._animate(deltaTime);
  55025. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55026. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55027. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55028. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55029. }
  55030. this._buffer.update(this._vertexData);
  55031. // Render
  55032. var effect = this._effectBase;
  55033. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55034. effect = this._effectFog;
  55035. }
  55036. engine.enableEffect(effect);
  55037. var viewMatrix = this._scene.getViewMatrix();
  55038. effect.setTexture("diffuseSampler", this._spriteTexture);
  55039. effect.setMatrix("view", viewMatrix);
  55040. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55041. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55042. // Fog
  55043. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55044. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55045. effect.setColor3("vFogColor", this._scene.fogColor);
  55046. }
  55047. // VBOs
  55048. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55049. // Draw order
  55050. engine.setDepthFunctionToLessOrEqual();
  55051. effect.setBool("alphaTest", true);
  55052. engine.setColorWrite(false);
  55053. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55054. engine.setColorWrite(true);
  55055. effect.setBool("alphaTest", false);
  55056. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55057. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55058. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55059. };
  55060. SpriteManager.prototype.dispose = function () {
  55061. if (this._buffer) {
  55062. this._buffer.dispose();
  55063. this._buffer = null;
  55064. }
  55065. if (this._indexBuffer) {
  55066. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55067. this._indexBuffer = null;
  55068. }
  55069. if (this._spriteTexture) {
  55070. this._spriteTexture.dispose();
  55071. this._spriteTexture = null;
  55072. }
  55073. // Remove from scene
  55074. var index = this._scene.spriteManagers.indexOf(this);
  55075. this._scene.spriteManagers.splice(index, 1);
  55076. // Callback
  55077. this.onDisposeObservable.notifyObservers(this);
  55078. this.onDisposeObservable.clear();
  55079. };
  55080. return SpriteManager;
  55081. }());
  55082. BABYLON.SpriteManager = SpriteManager;
  55083. })(BABYLON || (BABYLON = {}));
  55084. //# sourceMappingURL=babylon.spriteManager.js.map
  55085. var BABYLON;
  55086. (function (BABYLON) {
  55087. var Sprite = /** @class */ (function () {
  55088. function Sprite(name, manager) {
  55089. this.name = name;
  55090. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55091. this.width = 1.0;
  55092. this.height = 1.0;
  55093. this.angle = 0;
  55094. this.cellIndex = 0;
  55095. this.invertU = 0;
  55096. this.invertV = 0;
  55097. this.animations = new Array();
  55098. this.isPickable = false;
  55099. this._animationStarted = false;
  55100. this._loopAnimation = false;
  55101. this._fromIndex = 0;
  55102. this._toIndex = 0;
  55103. this._delay = 0;
  55104. this._direction = 1;
  55105. this._time = 0;
  55106. /**
  55107. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55108. */
  55109. this.isVisible = true;
  55110. this._manager = manager;
  55111. this._manager.sprites.push(this);
  55112. this.position = BABYLON.Vector3.Zero();
  55113. }
  55114. Object.defineProperty(Sprite.prototype, "size", {
  55115. get: function () {
  55116. return this.width;
  55117. },
  55118. set: function (value) {
  55119. this.width = value;
  55120. this.height = value;
  55121. },
  55122. enumerable: true,
  55123. configurable: true
  55124. });
  55125. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55126. this._fromIndex = from;
  55127. this._toIndex = to;
  55128. this._loopAnimation = loop;
  55129. this._delay = delay;
  55130. this._animationStarted = true;
  55131. this._direction = from < to ? 1 : -1;
  55132. this.cellIndex = from;
  55133. this._time = 0;
  55134. this._onAnimationEnd = onAnimationEnd;
  55135. };
  55136. Sprite.prototype.stopAnimation = function () {
  55137. this._animationStarted = false;
  55138. };
  55139. /** @hidden */
  55140. Sprite.prototype._animate = function (deltaTime) {
  55141. if (!this._animationStarted)
  55142. return;
  55143. this._time += deltaTime;
  55144. if (this._time > this._delay) {
  55145. this._time = this._time % this._delay;
  55146. this.cellIndex += this._direction;
  55147. if (this.cellIndex > this._toIndex) {
  55148. if (this._loopAnimation) {
  55149. this.cellIndex = this._fromIndex;
  55150. }
  55151. else {
  55152. this.cellIndex = this._toIndex;
  55153. this._animationStarted = false;
  55154. if (this._onAnimationEnd) {
  55155. this._onAnimationEnd();
  55156. }
  55157. if (this.disposeWhenFinishedAnimating) {
  55158. this.dispose();
  55159. }
  55160. }
  55161. }
  55162. }
  55163. };
  55164. Sprite.prototype.dispose = function () {
  55165. for (var i = 0; i < this._manager.sprites.length; i++) {
  55166. if (this._manager.sprites[i] == this) {
  55167. this._manager.sprites.splice(i, 1);
  55168. }
  55169. }
  55170. };
  55171. return Sprite;
  55172. }());
  55173. BABYLON.Sprite = Sprite;
  55174. })(BABYLON || (BABYLON = {}));
  55175. //# sourceMappingURL=babylon.sprite.js.map
  55176. var BABYLON;
  55177. (function (BABYLON) {
  55178. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55179. if (!BABYLON.PickingInfo) {
  55180. return null;
  55181. }
  55182. var pickingInfo = null;
  55183. if (!camera) {
  55184. if (!this.activeCamera) {
  55185. return null;
  55186. }
  55187. camera = this.activeCamera;
  55188. }
  55189. if (this.spriteManagers.length > 0) {
  55190. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55191. var spriteManager = this.spriteManagers[spriteIndex];
  55192. if (!spriteManager.isPickable) {
  55193. continue;
  55194. }
  55195. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55196. if (!result || !result.hit)
  55197. continue;
  55198. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55199. continue;
  55200. pickingInfo = result;
  55201. if (fastCheck) {
  55202. break;
  55203. }
  55204. }
  55205. }
  55206. return pickingInfo || new BABYLON.PickingInfo();
  55207. };
  55208. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55209. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55210. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55211. };
  55212. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55213. if (!this._tempSpritePickingRay) {
  55214. return null;
  55215. }
  55216. if (!camera) {
  55217. if (!this.activeCamera) {
  55218. return null;
  55219. }
  55220. camera = this.activeCamera;
  55221. }
  55222. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55223. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55224. };
  55225. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55226. if (this._pointerOverSprite === sprite) {
  55227. return;
  55228. }
  55229. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55230. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55231. }
  55232. this._pointerOverSprite = sprite;
  55233. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55234. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55235. }
  55236. };
  55237. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55238. return this._pointerOverSprite;
  55239. };
  55240. /**
  55241. * Defines the sprite scene component responsible to manage sprites
  55242. * in a given scene.
  55243. */
  55244. var SpriteSceneComponent = /** @class */ (function () {
  55245. /**
  55246. * Creates a new instance of the component for the given scene
  55247. * @param scene Defines the scene to register the component in
  55248. */
  55249. function SpriteSceneComponent(scene) {
  55250. /**
  55251. * The component name helpfull to identify the component in the list of scene components.
  55252. */
  55253. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55254. this.scene = scene;
  55255. this.scene.spriteManagers = new Array();
  55256. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55257. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55258. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55259. this._spritePredicate = function (sprite) {
  55260. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55261. };
  55262. }
  55263. /**
  55264. * Registers the component in a given scene
  55265. */
  55266. SpriteSceneComponent.prototype.register = function () {
  55267. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55268. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55269. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55270. };
  55271. /**
  55272. * Rebuilds the elements related to this component in case of
  55273. * context lost for instance.
  55274. */
  55275. SpriteSceneComponent.prototype.rebuild = function () {
  55276. /** Nothing to do for sprites */
  55277. };
  55278. /**
  55279. * Disposes the component and the associated ressources.
  55280. */
  55281. SpriteSceneComponent.prototype.dispose = function () {
  55282. this.scene.onBeforeSpritesRenderingObservable.clear();
  55283. this.scene.onAfterSpritesRenderingObservable.clear();
  55284. var spriteManagers = this.scene.spriteManagers;
  55285. while (spriteManagers.length) {
  55286. spriteManagers[0].dispose();
  55287. }
  55288. };
  55289. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55290. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55291. if (result) {
  55292. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55293. }
  55294. return result;
  55295. };
  55296. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55297. var scene = this.scene;
  55298. if (isMeshPicked) {
  55299. scene.setPointerOverSprite(null);
  55300. }
  55301. else {
  55302. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55303. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55304. scene.setPointerOverSprite(pickResult.pickedSprite);
  55305. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55306. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55307. }
  55308. else {
  55309. canvas.style.cursor = scene.hoverCursor;
  55310. }
  55311. }
  55312. else {
  55313. scene.setPointerOverSprite(null);
  55314. }
  55315. }
  55316. return pickResult;
  55317. };
  55318. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55319. var scene = this.scene;
  55320. scene._pickedDownSprite = null;
  55321. if (scene.spriteManagers.length > 0) {
  55322. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55323. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55324. if (pickResult.pickedSprite.actionManager) {
  55325. scene._pickedDownSprite = pickResult.pickedSprite;
  55326. switch (evt.button) {
  55327. case 0:
  55328. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55329. break;
  55330. case 1:
  55331. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55332. break;
  55333. case 2:
  55334. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55335. break;
  55336. }
  55337. if (pickResult.pickedSprite.actionManager) {
  55338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55339. }
  55340. }
  55341. }
  55342. }
  55343. return pickResult;
  55344. };
  55345. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55346. var scene = this.scene;
  55347. if (scene.spriteManagers.length > 0) {
  55348. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55349. if (spritePickResult) {
  55350. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55351. if (spritePickResult.pickedSprite.actionManager) {
  55352. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55353. if (spritePickResult.pickedSprite.actionManager) {
  55354. if (!this.scene._isPointerSwiping()) {
  55355. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55356. }
  55357. }
  55358. }
  55359. }
  55360. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55361. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55362. }
  55363. }
  55364. }
  55365. return pickResult;
  55366. };
  55367. return SpriteSceneComponent;
  55368. }());
  55369. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55370. })(BABYLON || (BABYLON = {}));
  55371. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55372. var BABYLON;
  55373. (function (BABYLON) {
  55374. /**
  55375. * @hidden
  55376. */
  55377. var IntersectionInfo = /** @class */ (function () {
  55378. function IntersectionInfo(bu, bv, distance) {
  55379. this.bu = bu;
  55380. this.bv = bv;
  55381. this.distance = distance;
  55382. this.faceId = 0;
  55383. this.subMeshId = 0;
  55384. }
  55385. return IntersectionInfo;
  55386. }());
  55387. BABYLON.IntersectionInfo = IntersectionInfo;
  55388. /**
  55389. * Information about the result of picking within a scene
  55390. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55391. */
  55392. var PickingInfo = /** @class */ (function () {
  55393. function PickingInfo() {
  55394. /**
  55395. * If the pick collided with an object
  55396. */
  55397. this.hit = false;
  55398. /**
  55399. * Distance away where the pick collided
  55400. */
  55401. this.distance = 0;
  55402. /**
  55403. * The location of pick collision
  55404. */
  55405. this.pickedPoint = null;
  55406. /**
  55407. * The mesh corresponding the the pick collision
  55408. */
  55409. this.pickedMesh = null;
  55410. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55411. this.bu = 0;
  55412. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55413. this.bv = 0;
  55414. /** The id of the face on the mesh that was picked */
  55415. this.faceId = -1;
  55416. /** Id of the the submesh that was picked */
  55417. this.subMeshId = 0;
  55418. /** If a sprite was picked, this will be the sprite the pick collided with */
  55419. this.pickedSprite = null;
  55420. /**
  55421. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55422. */
  55423. this.originMesh = null;
  55424. /**
  55425. * The ray that was used to perform the picking.
  55426. */
  55427. this.ray = null;
  55428. }
  55429. /**
  55430. * Gets the normal correspodning to the face the pick collided with
  55431. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55432. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55433. * @returns The normal correspodning to the face the pick collided with
  55434. */
  55435. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55436. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55437. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55438. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55439. return null;
  55440. }
  55441. var indices = this.pickedMesh.getIndices();
  55442. if (!indices) {
  55443. return null;
  55444. }
  55445. var result;
  55446. if (useVerticesNormals) {
  55447. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55448. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55449. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55450. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55451. normal0 = normal0.scale(this.bu);
  55452. normal1 = normal1.scale(this.bv);
  55453. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55454. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55455. }
  55456. else {
  55457. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55458. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55459. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55460. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55461. var p1p2 = vertex1.subtract(vertex2);
  55462. var p3p2 = vertex3.subtract(vertex2);
  55463. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55464. }
  55465. if (useWorldCoordinates) {
  55466. var wm = this.pickedMesh.getWorldMatrix();
  55467. if (this.pickedMesh.nonUniformScaling) {
  55468. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55469. wm = BABYLON.Tmp.Matrix[0];
  55470. wm.setTranslationFromFloats(0, 0, 0);
  55471. wm.invert();
  55472. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55473. wm = BABYLON.Tmp.Matrix[1];
  55474. }
  55475. result = BABYLON.Vector3.TransformNormal(result, wm);
  55476. }
  55477. result.normalize();
  55478. return result;
  55479. };
  55480. /**
  55481. * Gets the texture coordinates of where the pick occured
  55482. * @returns the vector containing the coordnates of the texture
  55483. */
  55484. PickingInfo.prototype.getTextureCoordinates = function () {
  55485. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55486. return null;
  55487. }
  55488. var indices = this.pickedMesh.getIndices();
  55489. if (!indices) {
  55490. return null;
  55491. }
  55492. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55493. if (!uvs) {
  55494. return null;
  55495. }
  55496. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55497. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55498. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55499. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55500. uv1 = uv1.scale(this.bu);
  55501. uv2 = uv2.scale(this.bv);
  55502. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55503. };
  55504. return PickingInfo;
  55505. }());
  55506. BABYLON.PickingInfo = PickingInfo;
  55507. })(BABYLON || (BABYLON = {}));
  55508. //# sourceMappingURL=babylon.pickingInfo.js.map
  55509. var BABYLON;
  55510. (function (BABYLON) {
  55511. var Ray = /** @class */ (function () {
  55512. function Ray(origin, direction, length) {
  55513. if (length === void 0) { length = Number.MAX_VALUE; }
  55514. this.origin = origin;
  55515. this.direction = direction;
  55516. this.length = length;
  55517. }
  55518. // Methods
  55519. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55520. var d = 0.0;
  55521. var maxValue = Number.MAX_VALUE;
  55522. var inv;
  55523. var min;
  55524. var max;
  55525. var temp;
  55526. if (Math.abs(this.direction.x) < 0.0000001) {
  55527. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55528. return false;
  55529. }
  55530. }
  55531. else {
  55532. inv = 1.0 / this.direction.x;
  55533. min = (minimum.x - this.origin.x) * inv;
  55534. max = (maximum.x - this.origin.x) * inv;
  55535. if (max === -Infinity) {
  55536. max = Infinity;
  55537. }
  55538. if (min > max) {
  55539. temp = min;
  55540. min = max;
  55541. max = temp;
  55542. }
  55543. d = Math.max(min, d);
  55544. maxValue = Math.min(max, maxValue);
  55545. if (d > maxValue) {
  55546. return false;
  55547. }
  55548. }
  55549. if (Math.abs(this.direction.y) < 0.0000001) {
  55550. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55551. return false;
  55552. }
  55553. }
  55554. else {
  55555. inv = 1.0 / this.direction.y;
  55556. min = (minimum.y - this.origin.y) * inv;
  55557. max = (maximum.y - this.origin.y) * inv;
  55558. if (max === -Infinity) {
  55559. max = Infinity;
  55560. }
  55561. if (min > max) {
  55562. temp = min;
  55563. min = max;
  55564. max = temp;
  55565. }
  55566. d = Math.max(min, d);
  55567. maxValue = Math.min(max, maxValue);
  55568. if (d > maxValue) {
  55569. return false;
  55570. }
  55571. }
  55572. if (Math.abs(this.direction.z) < 0.0000001) {
  55573. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55574. return false;
  55575. }
  55576. }
  55577. else {
  55578. inv = 1.0 / this.direction.z;
  55579. min = (minimum.z - this.origin.z) * inv;
  55580. max = (maximum.z - this.origin.z) * inv;
  55581. if (max === -Infinity) {
  55582. max = Infinity;
  55583. }
  55584. if (min > max) {
  55585. temp = min;
  55586. min = max;
  55587. max = temp;
  55588. }
  55589. d = Math.max(min, d);
  55590. maxValue = Math.min(max, maxValue);
  55591. if (d > maxValue) {
  55592. return false;
  55593. }
  55594. }
  55595. return true;
  55596. };
  55597. Ray.prototype.intersectsBox = function (box) {
  55598. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55599. };
  55600. Ray.prototype.intersectsSphere = function (sphere) {
  55601. var x = sphere.center.x - this.origin.x;
  55602. var y = sphere.center.y - this.origin.y;
  55603. var z = sphere.center.z - this.origin.z;
  55604. var pyth = (x * x) + (y * y) + (z * z);
  55605. var rr = sphere.radius * sphere.radius;
  55606. if (pyth <= rr) {
  55607. return true;
  55608. }
  55609. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55610. if (dot < 0.0) {
  55611. return false;
  55612. }
  55613. var temp = pyth - (dot * dot);
  55614. return temp <= rr;
  55615. };
  55616. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55617. if (!this._edge1) {
  55618. this._edge1 = BABYLON.Vector3.Zero();
  55619. this._edge2 = BABYLON.Vector3.Zero();
  55620. this._pvec = BABYLON.Vector3.Zero();
  55621. this._tvec = BABYLON.Vector3.Zero();
  55622. this._qvec = BABYLON.Vector3.Zero();
  55623. }
  55624. vertex1.subtractToRef(vertex0, this._edge1);
  55625. vertex2.subtractToRef(vertex0, this._edge2);
  55626. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55627. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55628. if (det === 0) {
  55629. return null;
  55630. }
  55631. var invdet = 1 / det;
  55632. this.origin.subtractToRef(vertex0, this._tvec);
  55633. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55634. if (bu < 0 || bu > 1.0) {
  55635. return null;
  55636. }
  55637. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55638. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55639. if (bv < 0 || bu + bv > 1.0) {
  55640. return null;
  55641. }
  55642. //check if the distance is longer than the predefined length.
  55643. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55644. if (distance > this.length) {
  55645. return null;
  55646. }
  55647. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55648. };
  55649. Ray.prototype.intersectsPlane = function (plane) {
  55650. var distance;
  55651. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55652. if (Math.abs(result1) < 9.99999997475243E-07) {
  55653. return null;
  55654. }
  55655. else {
  55656. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55657. distance = (-plane.d - result2) / result1;
  55658. if (distance < 0.0) {
  55659. if (distance < -9.99999997475243E-07) {
  55660. return null;
  55661. }
  55662. else {
  55663. return 0;
  55664. }
  55665. }
  55666. return distance;
  55667. }
  55668. };
  55669. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55670. var tm = BABYLON.Tmp.Matrix[0];
  55671. mesh.getWorldMatrix().invertToRef(tm);
  55672. if (this._tmpRay) {
  55673. Ray.TransformToRef(this, tm, this._tmpRay);
  55674. }
  55675. else {
  55676. this._tmpRay = Ray.Transform(this, tm);
  55677. }
  55678. return mesh.intersects(this._tmpRay, fastCheck);
  55679. };
  55680. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55681. if (results) {
  55682. results.length = 0;
  55683. }
  55684. else {
  55685. results = [];
  55686. }
  55687. for (var i = 0; i < meshes.length; i++) {
  55688. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55689. if (pickInfo.hit) {
  55690. results.push(pickInfo);
  55691. }
  55692. }
  55693. results.sort(this._comparePickingInfo);
  55694. return results;
  55695. };
  55696. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55697. if (pickingInfoA.distance < pickingInfoB.distance) {
  55698. return -1;
  55699. }
  55700. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55701. return 1;
  55702. }
  55703. else {
  55704. return 0;
  55705. }
  55706. };
  55707. /**
  55708. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55709. * @param sega the first point of the segment to test the intersection against
  55710. * @param segb the second point of the segment to test the intersection against
  55711. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55712. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55713. */
  55714. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55715. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55716. var u = segb.subtract(sega);
  55717. var v = rsegb.subtract(this.origin);
  55718. var w = sega.subtract(this.origin);
  55719. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55720. var b = BABYLON.Vector3.Dot(u, v);
  55721. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55722. var d = BABYLON.Vector3.Dot(u, w);
  55723. var e = BABYLON.Vector3.Dot(v, w);
  55724. var D = a * c - b * b; // always >= 0
  55725. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55726. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55727. // compute the line parameters of the two closest points
  55728. if (D < Ray.smallnum) { // the lines are almost parallel
  55729. sN = 0.0; // force using point P0 on segment S1
  55730. sD = 1.0; // to prevent possible division by 0.0 later
  55731. tN = e;
  55732. tD = c;
  55733. }
  55734. else { // get the closest points on the infinite lines
  55735. sN = (b * e - c * d);
  55736. tN = (a * e - b * d);
  55737. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55738. sN = 0.0;
  55739. tN = e;
  55740. tD = c;
  55741. }
  55742. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55743. sN = sD;
  55744. tN = e + b;
  55745. tD = c;
  55746. }
  55747. }
  55748. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55749. tN = 0.0;
  55750. // recompute sc for this edge
  55751. if (-d < 0.0) {
  55752. sN = 0.0;
  55753. }
  55754. else if (-d > a)
  55755. sN = sD;
  55756. else {
  55757. sN = -d;
  55758. sD = a;
  55759. }
  55760. }
  55761. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55762. tN = tD;
  55763. // recompute sc for this edge
  55764. if ((-d + b) < 0.0) {
  55765. sN = 0;
  55766. }
  55767. else if ((-d + b) > a) {
  55768. sN = sD;
  55769. }
  55770. else {
  55771. sN = (-d + b);
  55772. sD = a;
  55773. }
  55774. }
  55775. // finally do the division to get sc and tc
  55776. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55777. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55778. // get the difference of the two closest points
  55779. var qtc = v.multiplyByFloats(tc, tc, tc);
  55780. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55781. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55782. if (isIntersected) {
  55783. return qtc.length();
  55784. }
  55785. return -1;
  55786. };
  55787. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55788. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55789. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55790. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55791. this.direction.normalize();
  55792. return this;
  55793. };
  55794. // Statics
  55795. Ray.Zero = function () {
  55796. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55797. };
  55798. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55799. var result = Ray.Zero();
  55800. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55801. };
  55802. /**
  55803. * 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
  55804. * transformed to the given world matrix.
  55805. * @param origin The origin point
  55806. * @param end The end point
  55807. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55808. */
  55809. Ray.CreateNewFromTo = function (origin, end, world) {
  55810. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55811. var direction = end.subtract(origin);
  55812. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55813. direction.normalize();
  55814. return Ray.Transform(new Ray(origin, direction, length), world);
  55815. };
  55816. Ray.Transform = function (ray, matrix) {
  55817. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55818. Ray.TransformToRef(ray, matrix, result);
  55819. return result;
  55820. };
  55821. Ray.TransformToRef = function (ray, matrix, result) {
  55822. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55823. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55824. result.length = ray.length;
  55825. var dir = result.direction;
  55826. var len = dir.length();
  55827. if (!(len === 0 || len === 1)) {
  55828. var num = 1.0 / len;
  55829. dir.x *= num;
  55830. dir.y *= num;
  55831. dir.z *= num;
  55832. result.length *= len;
  55833. }
  55834. };
  55835. Ray.smallnum = 0.00000001;
  55836. Ray.rayl = 10e8;
  55837. return Ray;
  55838. }());
  55839. BABYLON.Ray = Ray;
  55840. })(BABYLON || (BABYLON = {}));
  55841. //# sourceMappingURL=babylon.ray.js.map
  55842. var BABYLON;
  55843. (function (BABYLON) {
  55844. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55845. if (boxMin.x > sphereCenter.x + sphereRadius)
  55846. return false;
  55847. if (sphereCenter.x - sphereRadius > boxMax.x)
  55848. return false;
  55849. if (boxMin.y > sphereCenter.y + sphereRadius)
  55850. return false;
  55851. if (sphereCenter.y - sphereRadius > boxMax.y)
  55852. return false;
  55853. if (boxMin.z > sphereCenter.z + sphereRadius)
  55854. return false;
  55855. if (sphereCenter.z - sphereRadius > boxMax.z)
  55856. return false;
  55857. return true;
  55858. };
  55859. var getLowestRoot = (function () {
  55860. var result = { root: 0, found: false };
  55861. return function (a, b, c, maxR) {
  55862. result.root = 0;
  55863. result.found = false;
  55864. var determinant = b * b - 4.0 * a * c;
  55865. if (determinant < 0)
  55866. return result;
  55867. var sqrtD = Math.sqrt(determinant);
  55868. var r1 = (-b - sqrtD) / (2.0 * a);
  55869. var r2 = (-b + sqrtD) / (2.0 * a);
  55870. if (r1 > r2) {
  55871. var temp = r2;
  55872. r2 = r1;
  55873. r1 = temp;
  55874. }
  55875. if (r1 > 0 && r1 < maxR) {
  55876. result.root = r1;
  55877. result.found = true;
  55878. return result;
  55879. }
  55880. if (r2 > 0 && r2 < maxR) {
  55881. result.root = r2;
  55882. result.found = true;
  55883. return result;
  55884. }
  55885. return result;
  55886. };
  55887. })();
  55888. /** @hidden */
  55889. var Collider = /** @class */ (function () {
  55890. function Collider() {
  55891. this._collisionPoint = BABYLON.Vector3.Zero();
  55892. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55893. this._tempVector = BABYLON.Vector3.Zero();
  55894. this._tempVector2 = BABYLON.Vector3.Zero();
  55895. this._tempVector3 = BABYLON.Vector3.Zero();
  55896. this._tempVector4 = BABYLON.Vector3.Zero();
  55897. this._edge = BABYLON.Vector3.Zero();
  55898. this._baseToVertex = BABYLON.Vector3.Zero();
  55899. this._destinationPoint = BABYLON.Vector3.Zero();
  55900. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55901. this._displacementVector = BABYLON.Vector3.Zero();
  55902. /** @hidden */
  55903. this._radius = BABYLON.Vector3.One();
  55904. /** @hidden */
  55905. this._retry = 0;
  55906. /** @hidden */
  55907. this._basePointWorld = BABYLON.Vector3.Zero();
  55908. this._velocityWorld = BABYLON.Vector3.Zero();
  55909. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55910. this._collisionMask = -1;
  55911. }
  55912. Object.defineProperty(Collider.prototype, "collisionMask", {
  55913. get: function () {
  55914. return this._collisionMask;
  55915. },
  55916. set: function (mask) {
  55917. this._collisionMask = !isNaN(mask) ? mask : -1;
  55918. },
  55919. enumerable: true,
  55920. configurable: true
  55921. });
  55922. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55923. /**
  55924. * Gets the plane normal used to compute the sliding response (in local space)
  55925. */
  55926. get: function () {
  55927. return this._slidePlaneNormal;
  55928. },
  55929. enumerable: true,
  55930. configurable: true
  55931. });
  55932. // Methods
  55933. /** @hidden */
  55934. Collider.prototype._initialize = function (source, dir, e) {
  55935. this._velocity = dir;
  55936. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55937. this._basePoint = source;
  55938. source.multiplyToRef(this._radius, this._basePointWorld);
  55939. dir.multiplyToRef(this._radius, this._velocityWorld);
  55940. this._velocityWorldLength = this._velocityWorld.length();
  55941. this._epsilon = e;
  55942. this.collisionFound = false;
  55943. };
  55944. /** @hidden */
  55945. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55946. pa.subtractToRef(point, this._tempVector);
  55947. pb.subtractToRef(point, this._tempVector2);
  55948. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55949. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55950. if (d < 0)
  55951. return false;
  55952. pc.subtractToRef(point, this._tempVector3);
  55953. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55954. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55955. if (d < 0)
  55956. return false;
  55957. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55958. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55959. return d >= 0;
  55960. };
  55961. /** @hidden */
  55962. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55963. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55964. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55965. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55966. return false;
  55967. }
  55968. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55969. return false;
  55970. return true;
  55971. };
  55972. /** @hidden */
  55973. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55974. var t0;
  55975. var embeddedInPlane = false;
  55976. //defensive programming, actually not needed.
  55977. if (!trianglePlaneArray) {
  55978. trianglePlaneArray = [];
  55979. }
  55980. if (!trianglePlaneArray[faceIndex]) {
  55981. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55982. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55983. }
  55984. var trianglePlane = trianglePlaneArray[faceIndex];
  55985. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55986. return;
  55987. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55988. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55989. if (normalDotVelocity == 0) {
  55990. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55991. return;
  55992. embeddedInPlane = true;
  55993. t0 = 0;
  55994. }
  55995. else {
  55996. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55997. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55998. if (t0 > t1) {
  55999. var temp = t1;
  56000. t1 = t0;
  56001. t0 = temp;
  56002. }
  56003. if (t0 > 1.0 || t1 < 0.0)
  56004. return;
  56005. if (t0 < 0)
  56006. t0 = 0;
  56007. if (t0 > 1.0)
  56008. t0 = 1.0;
  56009. }
  56010. this._collisionPoint.copyFromFloats(0, 0, 0);
  56011. var found = false;
  56012. var t = 1.0;
  56013. if (!embeddedInPlane) {
  56014. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56015. this._velocity.scaleToRef(t0, this._tempVector);
  56016. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56017. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56018. found = true;
  56019. t = t0;
  56020. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56021. }
  56022. }
  56023. if (!found) {
  56024. var velocitySquaredLength = this._velocity.lengthSquared();
  56025. var a = velocitySquaredLength;
  56026. this._basePoint.subtractToRef(p1, this._tempVector);
  56027. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56028. var c = this._tempVector.lengthSquared() - 1.0;
  56029. var lowestRoot = getLowestRoot(a, b, c, t);
  56030. if (lowestRoot.found) {
  56031. t = lowestRoot.root;
  56032. found = true;
  56033. this._collisionPoint.copyFrom(p1);
  56034. }
  56035. this._basePoint.subtractToRef(p2, this._tempVector);
  56036. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56037. c = this._tempVector.lengthSquared() - 1.0;
  56038. lowestRoot = getLowestRoot(a, b, c, t);
  56039. if (lowestRoot.found) {
  56040. t = lowestRoot.root;
  56041. found = true;
  56042. this._collisionPoint.copyFrom(p2);
  56043. }
  56044. this._basePoint.subtractToRef(p3, this._tempVector);
  56045. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56046. c = this._tempVector.lengthSquared() - 1.0;
  56047. lowestRoot = getLowestRoot(a, b, c, t);
  56048. if (lowestRoot.found) {
  56049. t = lowestRoot.root;
  56050. found = true;
  56051. this._collisionPoint.copyFrom(p3);
  56052. }
  56053. p2.subtractToRef(p1, this._edge);
  56054. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56055. var edgeSquaredLength = this._edge.lengthSquared();
  56056. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56057. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56058. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56059. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56060. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56061. lowestRoot = getLowestRoot(a, b, c, t);
  56062. if (lowestRoot.found) {
  56063. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56064. if (f >= 0.0 && f <= 1.0) {
  56065. t = lowestRoot.root;
  56066. found = true;
  56067. this._edge.scaleInPlace(f);
  56068. p1.addToRef(this._edge, this._collisionPoint);
  56069. }
  56070. }
  56071. p3.subtractToRef(p2, this._edge);
  56072. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56073. edgeSquaredLength = this._edge.lengthSquared();
  56074. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56075. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56076. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56077. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56078. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56079. lowestRoot = getLowestRoot(a, b, c, t);
  56080. if (lowestRoot.found) {
  56081. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56082. if (f >= 0.0 && f <= 1.0) {
  56083. t = lowestRoot.root;
  56084. found = true;
  56085. this._edge.scaleInPlace(f);
  56086. p2.addToRef(this._edge, this._collisionPoint);
  56087. }
  56088. }
  56089. p1.subtractToRef(p3, this._edge);
  56090. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56091. edgeSquaredLength = this._edge.lengthSquared();
  56092. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56093. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56094. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56095. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56096. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56097. lowestRoot = getLowestRoot(a, b, c, t);
  56098. if (lowestRoot.found) {
  56099. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56100. if (f >= 0.0 && f <= 1.0) {
  56101. t = lowestRoot.root;
  56102. found = true;
  56103. this._edge.scaleInPlace(f);
  56104. p3.addToRef(this._edge, this._collisionPoint);
  56105. }
  56106. }
  56107. }
  56108. if (found) {
  56109. var distToCollision = t * this._velocity.length();
  56110. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56111. if (!this.intersectionPoint) {
  56112. this.intersectionPoint = this._collisionPoint.clone();
  56113. }
  56114. else {
  56115. this.intersectionPoint.copyFrom(this._collisionPoint);
  56116. }
  56117. this._nearestDistance = distToCollision;
  56118. this.collisionFound = true;
  56119. }
  56120. }
  56121. };
  56122. /** @hidden */
  56123. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56124. for (var i = indexStart; i < indexEnd; i += 3) {
  56125. var p1 = pts[indices[i] - decal];
  56126. var p2 = pts[indices[i + 1] - decal];
  56127. var p3 = pts[indices[i + 2] - decal];
  56128. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56129. }
  56130. };
  56131. /** @hidden */
  56132. Collider.prototype._getResponse = function (pos, vel) {
  56133. pos.addToRef(vel, this._destinationPoint);
  56134. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56135. this._basePoint.addToRef(vel, pos);
  56136. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56137. this._slidePlaneNormal.normalize();
  56138. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56139. pos.addInPlace(this._displacementVector);
  56140. this.intersectionPoint.addInPlace(this._displacementVector);
  56141. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56142. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56143. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56144. };
  56145. return Collider;
  56146. }());
  56147. BABYLON.Collider = Collider;
  56148. })(BABYLON || (BABYLON = {}));
  56149. //# sourceMappingURL=babylon.collider.js.map
  56150. var BABYLON;
  56151. (function (BABYLON) {
  56152. //WebWorker code will be inserted to this variable.
  56153. /** @hidden */
  56154. BABYLON.CollisionWorker = "";
  56155. /** Defines supported task for worker process */
  56156. var WorkerTaskType;
  56157. (function (WorkerTaskType) {
  56158. /** Initialization */
  56159. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56160. /** Update of geometry */
  56161. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56162. /** Evaluate collision */
  56163. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56164. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56165. /** Defines kind of replies returned by worker */
  56166. var WorkerReplyType;
  56167. (function (WorkerReplyType) {
  56168. /** Success */
  56169. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56170. /** Unkown error */
  56171. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56172. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56173. /** @hidden */
  56174. var CollisionCoordinatorWorker = /** @class */ (function () {
  56175. function CollisionCoordinatorWorker() {
  56176. var _this = this;
  56177. this._scaledPosition = BABYLON.Vector3.Zero();
  56178. this._scaledVelocity = BABYLON.Vector3.Zero();
  56179. this.onMeshUpdated = function (transformNode) {
  56180. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56181. };
  56182. this.onGeometryUpdated = function (geometry) {
  56183. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56184. };
  56185. this._afterRender = function () {
  56186. if (!_this._init)
  56187. return;
  56188. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56189. return;
  56190. }
  56191. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56192. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56193. if (_this._runningUpdated > 4) {
  56194. return;
  56195. }
  56196. ++_this._runningUpdated;
  56197. var payload = {
  56198. updatedMeshes: _this._addUpdateMeshesList,
  56199. updatedGeometries: _this._addUpdateGeometriesList,
  56200. removedGeometries: _this._toRemoveGeometryArray,
  56201. removedMeshes: _this._toRemoveMeshesArray
  56202. };
  56203. var message = {
  56204. payload: payload,
  56205. taskType: WorkerTaskType.UPDATE
  56206. };
  56207. var serializable = [];
  56208. for (var id in payload.updatedGeometries) {
  56209. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56210. //prepare transferables
  56211. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56212. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56213. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56214. }
  56215. }
  56216. _this._worker.postMessage(message, serializable);
  56217. _this._addUpdateMeshesList = {};
  56218. _this._addUpdateGeometriesList = {};
  56219. _this._toRemoveGeometryArray = [];
  56220. _this._toRemoveMeshesArray = [];
  56221. };
  56222. this._onMessageFromWorker = function (e) {
  56223. var returnData = e.data;
  56224. if (returnData.error != WorkerReplyType.SUCCESS) {
  56225. //TODO what errors can be returned from the worker?
  56226. BABYLON.Tools.Warn("error returned from worker!");
  56227. return;
  56228. }
  56229. switch (returnData.taskType) {
  56230. case WorkerTaskType.INIT:
  56231. _this._init = true;
  56232. //Update the worked with ALL of the scene's current state
  56233. _this._scene.meshes.forEach(function (mesh) {
  56234. _this.onMeshAdded(mesh);
  56235. });
  56236. _this._scene.getGeometries().forEach(function (geometry) {
  56237. _this.onGeometryAdded(geometry);
  56238. });
  56239. break;
  56240. case WorkerTaskType.UPDATE:
  56241. _this._runningUpdated--;
  56242. break;
  56243. case WorkerTaskType.COLLIDE:
  56244. var returnPayload = returnData.payload;
  56245. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56246. return;
  56247. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56248. if (callback) {
  56249. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56250. if (mesh) {
  56251. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56252. }
  56253. }
  56254. //cleanup
  56255. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56256. break;
  56257. }
  56258. };
  56259. this._collisionsCallbackArray = [];
  56260. this._init = false;
  56261. this._runningUpdated = 0;
  56262. this._addUpdateMeshesList = {};
  56263. this._addUpdateGeometriesList = {};
  56264. this._toRemoveGeometryArray = [];
  56265. this._toRemoveMeshesArray = [];
  56266. }
  56267. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56268. if (!this._init)
  56269. return;
  56270. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56271. return;
  56272. position.divideToRef(collider._radius, this._scaledPosition);
  56273. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56274. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56275. var payload = {
  56276. collider: {
  56277. position: this._scaledPosition.asArray(),
  56278. velocity: this._scaledVelocity.asArray(),
  56279. radius: collider._radius.asArray()
  56280. },
  56281. collisionId: collisionIndex,
  56282. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56283. maximumRetry: maximumRetry
  56284. };
  56285. var message = {
  56286. payload: payload,
  56287. taskType: WorkerTaskType.COLLIDE
  56288. };
  56289. this._worker.postMessage(message);
  56290. };
  56291. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56292. this._scene = scene;
  56293. this._scene.registerAfterRender(this._afterRender);
  56294. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56295. this._worker = new Worker(workerUrl);
  56296. this._worker.onmessage = this._onMessageFromWorker;
  56297. var message = {
  56298. payload: {},
  56299. taskType: WorkerTaskType.INIT
  56300. };
  56301. this._worker.postMessage(message);
  56302. };
  56303. CollisionCoordinatorWorker.prototype.destroy = function () {
  56304. this._scene.unregisterAfterRender(this._afterRender);
  56305. this._worker.terminate();
  56306. };
  56307. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56308. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56309. this.onMeshUpdated(mesh);
  56310. };
  56311. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56312. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56313. };
  56314. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56315. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56316. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56317. this.onGeometryUpdated(geometry);
  56318. };
  56319. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56320. this._toRemoveGeometryArray.push(geometry.id);
  56321. };
  56322. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56323. var submeshes = [];
  56324. if (mesh.subMeshes) {
  56325. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56326. var boundingInfo = sm.getBoundingInfo();
  56327. return {
  56328. position: idx,
  56329. verticesStart: sm.verticesStart,
  56330. verticesCount: sm.verticesCount,
  56331. indexStart: sm.indexStart,
  56332. indexCount: sm.indexCount,
  56333. hasMaterial: !!sm.getMaterial(),
  56334. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56335. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56336. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56337. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56338. };
  56339. });
  56340. }
  56341. var geometryId = null;
  56342. if (mesh instanceof BABYLON.Mesh) {
  56343. var geometry = mesh.geometry;
  56344. geometryId = geometry ? geometry.id : null;
  56345. }
  56346. else if (mesh instanceof BABYLON.InstancedMesh) {
  56347. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56348. geometryId = geometry ? geometry.id : null;
  56349. }
  56350. var boundingInfo = mesh.getBoundingInfo();
  56351. return {
  56352. uniqueId: mesh.uniqueId,
  56353. id: mesh.id,
  56354. name: mesh.name,
  56355. geometryId: geometryId,
  56356. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56357. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56358. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56359. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56360. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56361. subMeshes: submeshes,
  56362. checkCollisions: mesh.checkCollisions
  56363. };
  56364. };
  56365. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56366. return {
  56367. id: geometry.id,
  56368. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56369. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56370. indices: new Uint32Array(geometry.getIndices() || []),
  56371. };
  56372. };
  56373. return CollisionCoordinatorWorker;
  56374. }());
  56375. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56376. /** @hidden */
  56377. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56378. function CollisionCoordinatorLegacy() {
  56379. this._scaledPosition = BABYLON.Vector3.Zero();
  56380. this._scaledVelocity = BABYLON.Vector3.Zero();
  56381. this._finalPosition = BABYLON.Vector3.Zero();
  56382. }
  56383. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56384. position.divideToRef(collider._radius, this._scaledPosition);
  56385. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56386. collider.collidedMesh = null;
  56387. collider._retry = 0;
  56388. collider._initialVelocity = this._scaledVelocity;
  56389. collider._initialPosition = this._scaledPosition;
  56390. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56391. this._finalPosition.multiplyInPlace(collider._radius);
  56392. //run the callback
  56393. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56394. };
  56395. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56396. this._scene = scene;
  56397. };
  56398. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56399. //Legacy need no destruction method.
  56400. };
  56401. //No update in legacy mode
  56402. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56403. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56404. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56405. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56406. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56407. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56408. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56409. if (excludedMesh === void 0) { excludedMesh = null; }
  56410. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56411. if (collider._retry >= maximumRetry) {
  56412. finalPosition.copyFrom(position);
  56413. return;
  56414. }
  56415. // Check if this is a mesh else camera or -1
  56416. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56417. collider._initialize(position, velocity, closeDistance);
  56418. // Check all meshes
  56419. for (var index = 0; index < this._scene.meshes.length; index++) {
  56420. var mesh = this._scene.meshes[index];
  56421. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56422. mesh._checkCollision(collider);
  56423. }
  56424. }
  56425. if (!collider.collisionFound) {
  56426. position.addToRef(velocity, finalPosition);
  56427. return;
  56428. }
  56429. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56430. collider._getResponse(position, velocity);
  56431. }
  56432. if (velocity.length() <= closeDistance) {
  56433. finalPosition.copyFrom(position);
  56434. return;
  56435. }
  56436. collider._retry++;
  56437. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56438. };
  56439. return CollisionCoordinatorLegacy;
  56440. }());
  56441. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56442. })(BABYLON || (BABYLON = {}));
  56443. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56444. var BABYLON;
  56445. (function (BABYLON) {
  56446. /**
  56447. * A particle represents one of the element emitted by a particle system.
  56448. * This is mainly define by its coordinates, direction, velocity and age.
  56449. */
  56450. var Particle = /** @class */ (function () {
  56451. /**
  56452. * Creates a new instance Particle
  56453. * @param particleSystem the particle system the particle belongs to
  56454. */
  56455. function Particle(
  56456. /**
  56457. * The particle system the particle belongs to.
  56458. */
  56459. particleSystem) {
  56460. this.particleSystem = particleSystem;
  56461. /**
  56462. * The world position of the particle in the scene.
  56463. */
  56464. this.position = BABYLON.Vector3.Zero();
  56465. /**
  56466. * The world direction of the particle in the scene.
  56467. */
  56468. this.direction = BABYLON.Vector3.Zero();
  56469. /**
  56470. * The color of the particle.
  56471. */
  56472. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56473. /**
  56474. * The color change of the particle per step.
  56475. */
  56476. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56477. /**
  56478. * Defines how long will the life of the particle be.
  56479. */
  56480. this.lifeTime = 1.0;
  56481. /**
  56482. * The current age of the particle.
  56483. */
  56484. this.age = 0;
  56485. /**
  56486. * The current size of the particle.
  56487. */
  56488. this.size = 0;
  56489. /**
  56490. * The current scale of the particle.
  56491. */
  56492. this.scale = new BABYLON.Vector2(1, 1);
  56493. /**
  56494. * The current angle of the particle.
  56495. */
  56496. this.angle = 0;
  56497. /**
  56498. * Defines how fast is the angle changing.
  56499. */
  56500. this.angularSpeed = 0;
  56501. /**
  56502. * Defines the cell index used by the particle to be rendered from a sprite.
  56503. */
  56504. this.cellIndex = 0;
  56505. /** @hidden */
  56506. this._attachedSubEmitters = null;
  56507. /** @hidden */
  56508. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56509. /** @hidden */
  56510. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56511. /** @hidden */
  56512. this._currentSize1 = 0;
  56513. /** @hidden */
  56514. this._currentSize2 = 0;
  56515. /** @hidden */
  56516. this._currentAngularSpeed1 = 0;
  56517. /** @hidden */
  56518. this._currentAngularSpeed2 = 0;
  56519. /** @hidden */
  56520. this._currentVelocity1 = 0;
  56521. /** @hidden */
  56522. this._currentVelocity2 = 0;
  56523. /** @hidden */
  56524. this._currentLimitVelocity1 = 0;
  56525. /** @hidden */
  56526. this._currentLimitVelocity2 = 0;
  56527. /** @hidden */
  56528. this._currentDrag1 = 0;
  56529. /** @hidden */
  56530. this._currentDrag2 = 0;
  56531. this.id = Particle._Count++;
  56532. if (!this.particleSystem.isAnimationSheetEnabled) {
  56533. return;
  56534. }
  56535. this.updateCellInfoFromSystem();
  56536. }
  56537. Particle.prototype.updateCellInfoFromSystem = function () {
  56538. this.cellIndex = this.particleSystem.startSpriteCellID;
  56539. };
  56540. /**
  56541. * Defines how the sprite cell index is updated for the particle
  56542. */
  56543. Particle.prototype.updateCellIndex = function () {
  56544. var offsetAge = this.age;
  56545. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56546. if (this.particleSystem.spriteRandomStartCell) {
  56547. if (this._randomCellOffset === undefined) {
  56548. this._randomCellOffset = Math.random() * this.lifeTime;
  56549. }
  56550. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56551. changeSpeed = 1;
  56552. offsetAge = this._randomCellOffset;
  56553. }
  56554. else {
  56555. offsetAge += this._randomCellOffset;
  56556. }
  56557. }
  56558. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56559. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56560. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56561. };
  56562. /** @hidden */
  56563. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56564. if (subEmitter.particleSystem.emitter.position) {
  56565. var emitterMesh = subEmitter.particleSystem.emitter;
  56566. emitterMesh.position.copyFrom(this.position);
  56567. if (subEmitter.inheritDirection) {
  56568. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56569. // Look at using Y as forward
  56570. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56571. }
  56572. }
  56573. else {
  56574. var emitterPosition = subEmitter.particleSystem.emitter;
  56575. emitterPosition.copyFrom(this.position);
  56576. }
  56577. // Set inheritedVelocityOffset to be used when new particles are created
  56578. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56579. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56580. };
  56581. /** @hidden */
  56582. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56583. var _this = this;
  56584. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56585. this._attachedSubEmitters.forEach(function (subEmitter) {
  56586. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56587. });
  56588. }
  56589. };
  56590. /** @hidden */
  56591. Particle.prototype._reset = function () {
  56592. this.age = 0;
  56593. this._currentColorGradient = null;
  56594. this._currentSizeGradient = null;
  56595. this._currentAngularSpeedGradient = null;
  56596. this._currentVelocityGradient = null;
  56597. this._currentLimitVelocityGradient = null;
  56598. this._currentDragGradient = null;
  56599. this.cellIndex = this.particleSystem.startSpriteCellID;
  56600. this._randomCellOffset = undefined;
  56601. };
  56602. /**
  56603. * Copy the properties of particle to another one.
  56604. * @param other the particle to copy the information to.
  56605. */
  56606. Particle.prototype.copyTo = function (other) {
  56607. other.position.copyFrom(this.position);
  56608. if (this._initialDirection) {
  56609. if (other._initialDirection) {
  56610. other._initialDirection.copyFrom(this._initialDirection);
  56611. }
  56612. else {
  56613. other._initialDirection = this._initialDirection.clone();
  56614. }
  56615. }
  56616. else {
  56617. other._initialDirection = null;
  56618. }
  56619. other.direction.copyFrom(this.direction);
  56620. other.color.copyFrom(this.color);
  56621. other.colorStep.copyFrom(this.colorStep);
  56622. other.lifeTime = this.lifeTime;
  56623. other.age = this.age;
  56624. other._randomCellOffset = this._randomCellOffset;
  56625. other.size = this.size;
  56626. other.scale.copyFrom(this.scale);
  56627. other.angle = this.angle;
  56628. other.angularSpeed = this.angularSpeed;
  56629. other.particleSystem = this.particleSystem;
  56630. other.cellIndex = this.cellIndex;
  56631. other.id = this.id;
  56632. other._attachedSubEmitters = this._attachedSubEmitters;
  56633. if (this._currentColorGradient) {
  56634. other._currentColorGradient = this._currentColorGradient;
  56635. other._currentColor1.copyFrom(this._currentColor1);
  56636. other._currentColor2.copyFrom(this._currentColor2);
  56637. }
  56638. if (this._currentSizeGradient) {
  56639. other._currentSizeGradient = this._currentSizeGradient;
  56640. other._currentSize1 = this._currentSize1;
  56641. other._currentSize2 = this._currentSize2;
  56642. }
  56643. if (this._currentAngularSpeedGradient) {
  56644. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56645. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56646. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56647. }
  56648. if (this._currentVelocityGradient) {
  56649. other._currentVelocityGradient = this._currentVelocityGradient;
  56650. other._currentVelocity1 = this._currentVelocity1;
  56651. other._currentVelocity2 = this._currentVelocity2;
  56652. }
  56653. if (this._currentLimitVelocityGradient) {
  56654. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56655. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56656. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56657. }
  56658. if (this._currentDragGradient) {
  56659. other._currentDragGradient = this._currentDragGradient;
  56660. other._currentDrag1 = this._currentDrag1;
  56661. other._currentDrag2 = this._currentDrag2;
  56662. }
  56663. if (this.particleSystem.isAnimationSheetEnabled) {
  56664. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56665. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56666. }
  56667. if (this.particleSystem.useRampGradients) {
  56668. other.remapData.copyFrom(this.remapData);
  56669. }
  56670. if (this._randomNoiseCoordinates1) {
  56671. if (other._randomNoiseCoordinates1) {
  56672. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56673. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56674. }
  56675. else {
  56676. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56677. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56678. }
  56679. }
  56680. };
  56681. Particle._Count = 0;
  56682. return Particle;
  56683. }());
  56684. BABYLON.Particle = Particle;
  56685. })(BABYLON || (BABYLON = {}));
  56686. //# sourceMappingURL=babylon.particle.js.map
  56687. var BABYLON;
  56688. (function (BABYLON) {
  56689. /**
  56690. * This represents the base class for particle system in Babylon.
  56691. * 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.
  56692. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56693. * @example https://doc.babylonjs.com/babylon101/particles
  56694. */
  56695. var BaseParticleSystem = /** @class */ (function () {
  56696. /**
  56697. * Instantiates a particle system.
  56698. * 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.
  56699. * @param name The name of the particle system
  56700. */
  56701. function BaseParticleSystem(name) {
  56702. /**
  56703. * List of animations used by the particle system.
  56704. */
  56705. this.animations = [];
  56706. /**
  56707. * The rendering group used by the Particle system to chose when to render.
  56708. */
  56709. this.renderingGroupId = 0;
  56710. /**
  56711. * The emitter represents the Mesh or position we are attaching the particle system to.
  56712. */
  56713. this.emitter = null;
  56714. /**
  56715. * The maximum number of particles to emit per frame
  56716. */
  56717. this.emitRate = 10;
  56718. /**
  56719. * If you want to launch only a few particles at once, that can be done, as well.
  56720. */
  56721. this.manualEmitCount = -1;
  56722. /**
  56723. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56724. */
  56725. this.updateSpeed = 0.01;
  56726. /**
  56727. * The amount of time the particle system is running (depends of the overall update speed).
  56728. */
  56729. this.targetStopDuration = 0;
  56730. /**
  56731. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56732. */
  56733. this.disposeOnStop = false;
  56734. /**
  56735. * Minimum power of emitting particles.
  56736. */
  56737. this.minEmitPower = 1;
  56738. /**
  56739. * Maximum power of emitting particles.
  56740. */
  56741. this.maxEmitPower = 1;
  56742. /**
  56743. * Minimum life time of emitting particles.
  56744. */
  56745. this.minLifeTime = 1;
  56746. /**
  56747. * Maximum life time of emitting particles.
  56748. */
  56749. this.maxLifeTime = 1;
  56750. /**
  56751. * Minimum Size of emitting particles.
  56752. */
  56753. this.minSize = 1;
  56754. /**
  56755. * Maximum Size of emitting particles.
  56756. */
  56757. this.maxSize = 1;
  56758. /**
  56759. * Minimum scale of emitting particles on X axis.
  56760. */
  56761. this.minScaleX = 1;
  56762. /**
  56763. * Maximum scale of emitting particles on X axis.
  56764. */
  56765. this.maxScaleX = 1;
  56766. /**
  56767. * Minimum scale of emitting particles on Y axis.
  56768. */
  56769. this.minScaleY = 1;
  56770. /**
  56771. * Maximum scale of emitting particles on Y axis.
  56772. */
  56773. this.maxScaleY = 1;
  56774. /**
  56775. * Gets or sets the minimal initial rotation in radians.
  56776. */
  56777. this.minInitialRotation = 0;
  56778. /**
  56779. * Gets or sets the maximal initial rotation in radians.
  56780. */
  56781. this.maxInitialRotation = 0;
  56782. /**
  56783. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56784. */
  56785. this.minAngularSpeed = 0;
  56786. /**
  56787. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56788. */
  56789. this.maxAngularSpeed = 0;
  56790. /**
  56791. * The layer mask we are rendering the particles through.
  56792. */
  56793. this.layerMask = 0x0FFFFFFF;
  56794. /**
  56795. * This can help using your own shader to render the particle system.
  56796. * The according effect will be created
  56797. */
  56798. this.customShader = null;
  56799. /**
  56800. * By default particle system starts as soon as they are created. This prevents the
  56801. * automatic start to happen and let you decide when to start emitting particles.
  56802. */
  56803. this.preventAutoStart = false;
  56804. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56805. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56806. /**
  56807. * Callback triggered when the particle animation is ending.
  56808. */
  56809. this.onAnimationEnd = null;
  56810. /**
  56811. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56812. */
  56813. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56814. /**
  56815. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56816. * to override the particles.
  56817. */
  56818. this.forceDepthWrite = false;
  56819. /** 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 */
  56820. this.preWarmCycles = 0;
  56821. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56822. this.preWarmStepOffset = 1;
  56823. /**
  56824. * 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)
  56825. */
  56826. this.spriteCellChangeSpeed = 1;
  56827. /**
  56828. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56829. */
  56830. this.startSpriteCellID = 0;
  56831. /**
  56832. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56833. */
  56834. this.endSpriteCellID = 0;
  56835. /**
  56836. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56837. */
  56838. this.spriteCellWidth = 0;
  56839. /**
  56840. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56841. */
  56842. this.spriteCellHeight = 0;
  56843. /**
  56844. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56845. */
  56846. this.spriteRandomStartCell = false;
  56847. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56848. this.translationPivot = new BABYLON.Vector2(0, 0);
  56849. /**
  56850. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  56851. */
  56852. this.beginAnimationOnStart = false;
  56853. /**
  56854. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  56855. */
  56856. this.beginAnimationFrom = 0;
  56857. /**
  56858. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  56859. */
  56860. this.beginAnimationTo = 60;
  56861. /**
  56862. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  56863. */
  56864. this.beginAnimationLoop = false;
  56865. /**
  56866. * You can use gravity if you want to give an orientation to your particles.
  56867. */
  56868. this.gravity = BABYLON.Vector3.Zero();
  56869. this._colorGradients = null;
  56870. this._sizeGradients = null;
  56871. this._lifeTimeGradients = null;
  56872. this._angularSpeedGradients = null;
  56873. this._velocityGradients = null;
  56874. this._limitVelocityGradients = null;
  56875. this._dragGradients = null;
  56876. this._emitRateGradients = null;
  56877. this._startSizeGradients = null;
  56878. this._rampGradients = null;
  56879. this._colorRemapGradients = null;
  56880. this._alphaRemapGradients = null;
  56881. /**
  56882. * Defines the delay in milliseconds before starting the system (0 by default)
  56883. */
  56884. this.startDelay = 0;
  56885. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56886. this.limitVelocityDamping = 0.4;
  56887. /**
  56888. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56889. */
  56890. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56891. /**
  56892. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56893. */
  56894. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56895. /**
  56896. * Color the particle will have at the end of its lifetime
  56897. */
  56898. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56899. /**
  56900. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56901. */
  56902. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56903. /** @hidden */
  56904. this._isSubEmitter = false;
  56905. /**
  56906. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56907. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  56908. */
  56909. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  56910. this._isBillboardBased = true;
  56911. /**
  56912. * Local cache of defines for image processing.
  56913. */
  56914. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56915. this.id = name;
  56916. this.name = name;
  56917. }
  56918. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56919. /**
  56920. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56921. */
  56922. get: function () {
  56923. return this._isAnimationSheetEnabled;
  56924. },
  56925. set: function (value) {
  56926. if (this._isAnimationSheetEnabled == value) {
  56927. return;
  56928. }
  56929. this._isAnimationSheetEnabled = value;
  56930. this._reset();
  56931. },
  56932. enumerable: true,
  56933. configurable: true
  56934. });
  56935. /**
  56936. * Get hosting scene
  56937. * @returns the scene
  56938. */
  56939. BaseParticleSystem.prototype.getScene = function () {
  56940. return this._scene;
  56941. };
  56942. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56943. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56944. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56945. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56946. };
  56947. /**
  56948. * Gets the current list of drag gradients.
  56949. * You must use addDragGradient and removeDragGradient to udpate this list
  56950. * @returns the list of drag gradients
  56951. */
  56952. BaseParticleSystem.prototype.getDragGradients = function () {
  56953. return this._dragGradients;
  56954. };
  56955. /**
  56956. * Gets the current list of limit velocity gradients.
  56957. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56958. * @returns the list of limit velocity gradients
  56959. */
  56960. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56961. return this._limitVelocityGradients;
  56962. };
  56963. /**
  56964. * Gets the current list of color gradients.
  56965. * You must use addColorGradient and removeColorGradient to udpate this list
  56966. * @returns the list of color gradients
  56967. */
  56968. BaseParticleSystem.prototype.getColorGradients = function () {
  56969. return this._colorGradients;
  56970. };
  56971. /**
  56972. * Gets the current list of size gradients.
  56973. * You must use addSizeGradient and removeSizeGradient to udpate this list
  56974. * @returns the list of size gradients
  56975. */
  56976. BaseParticleSystem.prototype.getSizeGradients = function () {
  56977. return this._sizeGradients;
  56978. };
  56979. /**
  56980. * Gets the current list of color remap gradients.
  56981. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  56982. * @returns the list of color remap gradients
  56983. */
  56984. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  56985. return this._colorRemapGradients;
  56986. };
  56987. /**
  56988. * Gets the current list of alpha remap gradients.
  56989. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  56990. * @returns the list of alpha remap gradients
  56991. */
  56992. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  56993. return this._alphaRemapGradients;
  56994. };
  56995. /**
  56996. * Gets the current list of life time gradients.
  56997. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  56998. * @returns the list of life time gradients
  56999. */
  57000. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57001. return this._lifeTimeGradients;
  57002. };
  57003. /**
  57004. * Gets the current list of angular speed gradients.
  57005. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57006. * @returns the list of angular speed gradients
  57007. */
  57008. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57009. return this._angularSpeedGradients;
  57010. };
  57011. /**
  57012. * Gets the current list of velocity gradients.
  57013. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57014. * @returns the list of velocity gradients
  57015. */
  57016. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57017. return this._velocityGradients;
  57018. };
  57019. /**
  57020. * Gets the current list of start size gradients.
  57021. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57022. * @returns the list of start size gradients
  57023. */
  57024. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57025. return this._startSizeGradients;
  57026. };
  57027. /**
  57028. * Gets the current list of emit rate gradients.
  57029. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57030. * @returns the list of emit rate gradients
  57031. */
  57032. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57033. return this._emitRateGradients;
  57034. };
  57035. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57036. /**
  57037. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57038. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57039. */
  57040. get: function () {
  57041. if (this.particleEmitterType.direction1) {
  57042. return this.particleEmitterType.direction1;
  57043. }
  57044. return BABYLON.Vector3.Zero();
  57045. },
  57046. set: function (value) {
  57047. if (this.particleEmitterType.direction1) {
  57048. this.particleEmitterType.direction1 = value;
  57049. }
  57050. },
  57051. enumerable: true,
  57052. configurable: true
  57053. });
  57054. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57055. /**
  57056. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57057. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57058. */
  57059. get: function () {
  57060. if (this.particleEmitterType.direction2) {
  57061. return this.particleEmitterType.direction2;
  57062. }
  57063. return BABYLON.Vector3.Zero();
  57064. },
  57065. set: function (value) {
  57066. if (this.particleEmitterType.direction2) {
  57067. this.particleEmitterType.direction2 = value;
  57068. }
  57069. },
  57070. enumerable: true,
  57071. configurable: true
  57072. });
  57073. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57074. /**
  57075. * 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.
  57076. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57077. */
  57078. get: function () {
  57079. if (this.particleEmitterType.minEmitBox) {
  57080. return this.particleEmitterType.minEmitBox;
  57081. }
  57082. return BABYLON.Vector3.Zero();
  57083. },
  57084. set: function (value) {
  57085. if (this.particleEmitterType.minEmitBox) {
  57086. this.particleEmitterType.minEmitBox = value;
  57087. }
  57088. },
  57089. enumerable: true,
  57090. configurable: true
  57091. });
  57092. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57093. /**
  57094. * 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.
  57095. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57096. */
  57097. get: function () {
  57098. if (this.particleEmitterType.maxEmitBox) {
  57099. return this.particleEmitterType.maxEmitBox;
  57100. }
  57101. return BABYLON.Vector3.Zero();
  57102. },
  57103. set: function (value) {
  57104. if (this.particleEmitterType.maxEmitBox) {
  57105. this.particleEmitterType.maxEmitBox = value;
  57106. }
  57107. },
  57108. enumerable: true,
  57109. configurable: true
  57110. });
  57111. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57112. /**
  57113. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57114. */
  57115. get: function () {
  57116. return this._isBillboardBased;
  57117. },
  57118. set: function (value) {
  57119. if (this._isBillboardBased === value) {
  57120. return;
  57121. }
  57122. this._isBillboardBased = value;
  57123. this._reset();
  57124. },
  57125. enumerable: true,
  57126. configurable: true
  57127. });
  57128. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57129. /**
  57130. * Gets the image processing configuration used either in this material.
  57131. */
  57132. get: function () {
  57133. return this._imageProcessingConfiguration;
  57134. },
  57135. /**
  57136. * Sets the Default image processing configuration used either in the this material.
  57137. *
  57138. * If sets to null, the scene one is in use.
  57139. */
  57140. set: function (value) {
  57141. this._attachImageProcessingConfiguration(value);
  57142. },
  57143. enumerable: true,
  57144. configurable: true
  57145. });
  57146. /**
  57147. * Attaches a new image processing configuration to the Standard Material.
  57148. * @param configuration
  57149. */
  57150. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57151. if (configuration === this._imageProcessingConfiguration) {
  57152. return;
  57153. }
  57154. // Pick the scene configuration if needed.
  57155. if (!configuration) {
  57156. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57157. }
  57158. else {
  57159. this._imageProcessingConfiguration = configuration;
  57160. }
  57161. };
  57162. /** @hidden */
  57163. BaseParticleSystem.prototype._reset = function () {
  57164. };
  57165. /** @hidden */
  57166. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57167. if (!gradients) {
  57168. return this;
  57169. }
  57170. var index = 0;
  57171. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57172. var valueGradient = gradients_1[_i];
  57173. if (valueGradient.gradient === gradient) {
  57174. gradients.splice(index, 1);
  57175. break;
  57176. }
  57177. index++;
  57178. }
  57179. if (texture) {
  57180. texture.dispose();
  57181. }
  57182. return this;
  57183. };
  57184. /**
  57185. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57186. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57187. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57188. * @returns the emitter
  57189. */
  57190. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57191. var particleEmitter = new BABYLON.PointParticleEmitter();
  57192. particleEmitter.direction1 = direction1;
  57193. particleEmitter.direction2 = direction2;
  57194. this.particleEmitterType = particleEmitter;
  57195. return particleEmitter;
  57196. };
  57197. /**
  57198. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57199. * @param radius The radius of the hemisphere to emit from
  57200. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57201. * @returns the emitter
  57202. */
  57203. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57204. if (radius === void 0) { radius = 1; }
  57205. if (radiusRange === void 0) { radiusRange = 1; }
  57206. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57207. this.particleEmitterType = particleEmitter;
  57208. return particleEmitter;
  57209. };
  57210. /**
  57211. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57212. * @param radius The radius of the sphere to emit from
  57213. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57214. * @returns the emitter
  57215. */
  57216. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57217. if (radius === void 0) { radius = 1; }
  57218. if (radiusRange === void 0) { radiusRange = 1; }
  57219. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57220. this.particleEmitterType = particleEmitter;
  57221. return particleEmitter;
  57222. };
  57223. /**
  57224. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57225. * @param radius The radius of the sphere to emit from
  57226. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57227. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57228. * @returns the emitter
  57229. */
  57230. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57231. if (radius === void 0) { radius = 1; }
  57232. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57233. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57234. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57235. this.particleEmitterType = particleEmitter;
  57236. return particleEmitter;
  57237. };
  57238. /**
  57239. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57240. * @param radius The radius of the emission cylinder
  57241. * @param height The height of the emission cylinder
  57242. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57243. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57244. * @returns the emitter
  57245. */
  57246. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57247. if (radius === void 0) { radius = 1; }
  57248. if (height === void 0) { height = 1; }
  57249. if (radiusRange === void 0) { radiusRange = 1; }
  57250. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57251. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57252. this.particleEmitterType = particleEmitter;
  57253. return particleEmitter;
  57254. };
  57255. /**
  57256. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57257. * @param radius The radius of the cylinder to emit from
  57258. * @param height The height of the emission cylinder
  57259. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57260. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57261. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57262. * @returns the emitter
  57263. */
  57264. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57265. if (radius === void 0) { radius = 1; }
  57266. if (height === void 0) { height = 1; }
  57267. if (radiusRange === void 0) { radiusRange = 1; }
  57268. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57269. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57270. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57271. this.particleEmitterType = particleEmitter;
  57272. return particleEmitter;
  57273. };
  57274. /**
  57275. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57276. * @param radius The radius of the cone to emit from
  57277. * @param angle The base angle of the cone
  57278. * @returns the emitter
  57279. */
  57280. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57281. if (radius === void 0) { radius = 1; }
  57282. if (angle === void 0) { angle = Math.PI / 4; }
  57283. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57284. this.particleEmitterType = particleEmitter;
  57285. return particleEmitter;
  57286. };
  57287. /**
  57288. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57289. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57290. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57291. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57292. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57293. * @returns the emitter
  57294. */
  57295. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57296. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57297. this.particleEmitterType = particleEmitter;
  57298. this.direction1 = direction1;
  57299. this.direction2 = direction2;
  57300. this.minEmitBox = minEmitBox;
  57301. this.maxEmitBox = maxEmitBox;
  57302. return particleEmitter;
  57303. };
  57304. /**
  57305. * Source color is added to the destination color without alpha affecting the result
  57306. */
  57307. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57308. /**
  57309. * Blend current color and particle color using particle’s alpha
  57310. */
  57311. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57312. /**
  57313. * Add current color and particle color multiplied by particle’s alpha
  57314. */
  57315. BaseParticleSystem.BLENDMODE_ADD = 2;
  57316. /**
  57317. * Multiply current color with particle color
  57318. */
  57319. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57320. /**
  57321. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57322. */
  57323. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57324. return BaseParticleSystem;
  57325. }());
  57326. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57327. })(BABYLON || (BABYLON = {}));
  57328. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57329. var BABYLON;
  57330. (function (BABYLON) {
  57331. /**
  57332. * This represents a particle system in Babylon.
  57333. * 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.
  57334. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57335. * @example https://doc.babylonjs.com/babylon101/particles
  57336. */
  57337. var ParticleSystem = /** @class */ (function (_super) {
  57338. __extends(ParticleSystem, _super);
  57339. /**
  57340. * Instantiates a particle system.
  57341. * 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.
  57342. * @param name The name of the particle system
  57343. * @param capacity The max number of particles alive at the same time
  57344. * @param scene The scene the particle system belongs to
  57345. * @param customEffect a custom effect used to change the way particles are rendered by default
  57346. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57347. * @param epsilon Offset used to render the particles
  57348. */
  57349. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57350. if (customEffect === void 0) { customEffect = null; }
  57351. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57352. if (epsilon === void 0) { epsilon = 0.01; }
  57353. var _this = _super.call(this, name) || this;
  57354. /**
  57355. * @hidden
  57356. */
  57357. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57358. /**
  57359. * An event triggered when the system is disposed
  57360. */
  57361. _this.onDisposeObservable = new BABYLON.Observable();
  57362. _this._particles = new Array();
  57363. _this._stockParticles = new Array();
  57364. _this._newPartsExcess = 0;
  57365. _this._vertexBuffers = {};
  57366. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57367. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57368. _this._scaledDirection = BABYLON.Vector3.Zero();
  57369. _this._scaledGravity = BABYLON.Vector3.Zero();
  57370. _this._currentRenderId = -1;
  57371. _this._useInstancing = false;
  57372. _this._started = false;
  57373. _this._stopped = false;
  57374. _this._actualFrame = 0;
  57375. /** @hidden */
  57376. _this._currentEmitRate1 = 0;
  57377. /** @hidden */
  57378. _this._currentEmitRate2 = 0;
  57379. /** @hidden */
  57380. _this._currentStartSize1 = 0;
  57381. /** @hidden */
  57382. _this._currentStartSize2 = 0;
  57383. _this._rawTextureWidth = 256;
  57384. _this._useRampGradients = false;
  57385. /**
  57386. * @hidden
  57387. * If the particle systems emitter should be disposed when the particle system is disposed
  57388. */
  57389. _this._disposeEmitterOnDispose = false;
  57390. // start of sub system methods
  57391. /**
  57392. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57393. * Its lifetime will start back at 0.
  57394. */
  57395. _this.recycleParticle = function (particle) {
  57396. // move particle from activeParticle list to stock particles
  57397. var lastParticle = _this._particles.pop();
  57398. if (lastParticle !== particle) {
  57399. lastParticle.copyTo(particle);
  57400. }
  57401. _this._stockParticles.push(lastParticle);
  57402. };
  57403. _this._createParticle = function () {
  57404. var particle;
  57405. if (_this._stockParticles.length !== 0) {
  57406. particle = _this._stockParticles.pop();
  57407. particle._reset();
  57408. }
  57409. else {
  57410. particle = new BABYLON.Particle(_this);
  57411. }
  57412. // Attach emitters
  57413. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57414. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57415. particle._attachedSubEmitters = [];
  57416. subEmitters.forEach(function (subEmitter) {
  57417. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57418. var newEmitter = subEmitter.clone();
  57419. particle._attachedSubEmitters.push(newEmitter);
  57420. newEmitter.particleSystem.start();
  57421. }
  57422. });
  57423. }
  57424. return particle;
  57425. };
  57426. _this._emitFromParticle = function (particle) {
  57427. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57428. return;
  57429. }
  57430. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57431. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57432. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57433. var subSystem = subEmitter.clone();
  57434. particle._inheritParticleInfoToSubEmitter(subSystem);
  57435. subSystem.particleSystem._rootParticleSystem = _this;
  57436. _this.activeSubSystems.push(subSystem.particleSystem);
  57437. subSystem.particleSystem.start();
  57438. }
  57439. });
  57440. };
  57441. _this._capacity = capacity;
  57442. _this._epsilon = epsilon;
  57443. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57444. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57445. // Setup the default processing configuration to the scene.
  57446. _this._attachImageProcessingConfiguration(null);
  57447. _this._customEffect = customEffect;
  57448. _this._scene.particleSystems.push(_this);
  57449. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57450. _this._createIndexBuffer();
  57451. _this._createVertexBuffers();
  57452. // Default emitter type
  57453. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57454. // Update
  57455. _this.updateFunction = function (particles) {
  57456. var noiseTextureSize = null;
  57457. var noiseTextureData = null;
  57458. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57459. noiseTextureSize = _this.noiseTexture.getSize();
  57460. noiseTextureData = (_this.noiseTexture.getContent());
  57461. }
  57462. var _loop_1 = function () {
  57463. particle = particles[index];
  57464. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57465. var previousAge = particle.age;
  57466. particle.age += scaledUpdateSpeed;
  57467. // Evaluate step to death
  57468. if (particle.age > particle.lifeTime) {
  57469. var diff = particle.age - previousAge;
  57470. var oldDiff = particle.lifeTime - previousAge;
  57471. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57472. particle.age = particle.lifeTime;
  57473. }
  57474. var ratio = particle.age / particle.lifeTime;
  57475. // Color
  57476. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57477. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57478. if (currentGradient !== particle._currentColorGradient) {
  57479. particle._currentColor1.copyFrom(particle._currentColor2);
  57480. nextGradient.getColorToRef(particle._currentColor2);
  57481. particle._currentColorGradient = currentGradient;
  57482. }
  57483. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57484. });
  57485. }
  57486. else {
  57487. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57488. particle.color.addInPlace(_this._scaledColorStep);
  57489. if (particle.color.a < 0) {
  57490. particle.color.a = 0;
  57491. }
  57492. }
  57493. // Angular speed
  57494. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57495. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57496. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57497. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57498. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57499. particle._currentAngularSpeedGradient = currentGradient;
  57500. }
  57501. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57502. });
  57503. }
  57504. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57505. // Direction
  57506. var directionScale = scaledUpdateSpeed;
  57507. /// Velocity
  57508. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57509. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57510. if (currentGradient !== particle._currentVelocityGradient) {
  57511. particle._currentVelocity1 = particle._currentVelocity2;
  57512. particle._currentVelocity2 = nextGradient.getFactor();
  57513. particle._currentVelocityGradient = currentGradient;
  57514. }
  57515. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57516. });
  57517. }
  57518. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57519. /// Limit velocity
  57520. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57521. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57522. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57523. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57524. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57525. particle._currentLimitVelocityGradient = currentGradient;
  57526. }
  57527. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57528. var currentVelocity = particle.direction.length();
  57529. if (currentVelocity > limitVelocity) {
  57530. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57531. }
  57532. });
  57533. }
  57534. /// Drag
  57535. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57536. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57537. if (currentGradient !== particle._currentDragGradient) {
  57538. particle._currentDrag1 = particle._currentDrag2;
  57539. particle._currentDrag2 = nextGradient.getFactor();
  57540. particle._currentDragGradient = currentGradient;
  57541. }
  57542. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57543. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57544. });
  57545. }
  57546. particle.position.addInPlace(_this._scaledDirection);
  57547. // Noise
  57548. if (noiseTextureData && noiseTextureSize) {
  57549. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57550. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57551. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57552. var force = BABYLON.Tmp.Vector3[0];
  57553. var scaledForce = BABYLON.Tmp.Vector3[1];
  57554. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57555. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57556. particle.direction.addInPlace(scaledForce);
  57557. }
  57558. // Gravity
  57559. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57560. particle.direction.addInPlace(_this._scaledGravity);
  57561. // Size
  57562. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57563. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57564. if (currentGradient !== particle._currentSizeGradient) {
  57565. particle._currentSize1 = particle._currentSize2;
  57566. particle._currentSize2 = nextGradient.getFactor();
  57567. particle._currentSizeGradient = currentGradient;
  57568. }
  57569. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57570. });
  57571. }
  57572. // Remap data
  57573. if (_this._useRampGradients) {
  57574. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57575. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57576. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57577. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57578. particle.remapData.x = min;
  57579. particle.remapData.y = max - min;
  57580. });
  57581. }
  57582. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57583. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57584. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57585. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57586. particle.remapData.z = min;
  57587. particle.remapData.w = max - min;
  57588. });
  57589. }
  57590. }
  57591. if (_this._isAnimationSheetEnabled) {
  57592. particle.updateCellIndex();
  57593. }
  57594. // Update the position of the attached sub-emitters to match their attached particle
  57595. particle._inheritParticleInfoToSubEmitters();
  57596. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57597. _this._emitFromParticle(particle);
  57598. if (particle._attachedSubEmitters) {
  57599. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57600. subEmitter.particleSystem.disposeOnStop = true;
  57601. subEmitter.particleSystem.stop();
  57602. });
  57603. particle._attachedSubEmitters = null;
  57604. }
  57605. _this.recycleParticle(particle);
  57606. index--;
  57607. return "continue";
  57608. }
  57609. };
  57610. var particle;
  57611. for (var index = 0; index < particles.length; index++) {
  57612. _loop_1();
  57613. }
  57614. };
  57615. return _this;
  57616. }
  57617. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57618. /**
  57619. * Sets a callback that will be triggered when the system is disposed
  57620. */
  57621. set: function (callback) {
  57622. if (this._onDisposeObserver) {
  57623. this.onDisposeObservable.remove(this._onDisposeObserver);
  57624. }
  57625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57626. },
  57627. enumerable: true,
  57628. configurable: true
  57629. });
  57630. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57631. /** Gets or sets a boolean indicating that ramp gradients must be used
  57632. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57633. */
  57634. get: function () {
  57635. return this._useRampGradients;
  57636. },
  57637. set: function (value) {
  57638. if (this._useRampGradients === value) {
  57639. return;
  57640. }
  57641. this._useRampGradients = value;
  57642. this._resetEffect();
  57643. },
  57644. enumerable: true,
  57645. configurable: true
  57646. });
  57647. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57648. //end of Sub-emitter
  57649. /**
  57650. * Gets the current list of active particles
  57651. */
  57652. get: function () {
  57653. return this._particles;
  57654. },
  57655. enumerable: true,
  57656. configurable: true
  57657. });
  57658. /**
  57659. * Returns the string "ParticleSystem"
  57660. * @returns a string containing the class name
  57661. */
  57662. ParticleSystem.prototype.getClassName = function () {
  57663. return "ParticleSystem";
  57664. };
  57665. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57666. var newGradient = new BABYLON.FactorGradient();
  57667. newGradient.gradient = gradient;
  57668. newGradient.factor1 = factor;
  57669. newGradient.factor2 = factor2;
  57670. factorGradients.push(newGradient);
  57671. factorGradients.sort(function (a, b) {
  57672. if (a.gradient < b.gradient) {
  57673. return -1;
  57674. }
  57675. else if (a.gradient > b.gradient) {
  57676. return 1;
  57677. }
  57678. return 0;
  57679. });
  57680. };
  57681. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57682. if (!factorGradients) {
  57683. return;
  57684. }
  57685. var index = 0;
  57686. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57687. var factorGradient = factorGradients_1[_i];
  57688. if (factorGradient.gradient === gradient) {
  57689. factorGradients.splice(index, 1);
  57690. break;
  57691. }
  57692. index++;
  57693. }
  57694. };
  57695. /**
  57696. * Adds a new life time gradient
  57697. * @param gradient defines the gradient to use (between 0 and 1)
  57698. * @param factor defines the life time factor to affect to the specified gradient
  57699. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57700. * @returns the current particle system
  57701. */
  57702. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57703. if (!this._lifeTimeGradients) {
  57704. this._lifeTimeGradients = [];
  57705. }
  57706. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57707. return this;
  57708. };
  57709. /**
  57710. * Remove a specific life time gradient
  57711. * @param gradient defines the gradient to remove
  57712. * @returns the current particle system
  57713. */
  57714. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57715. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57716. return this;
  57717. };
  57718. /**
  57719. * Adds a new size gradient
  57720. * @param gradient defines the gradient to use (between 0 and 1)
  57721. * @param factor defines the size factor to affect to the specified gradient
  57722. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57723. * @returns the current particle system
  57724. */
  57725. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57726. if (!this._sizeGradients) {
  57727. this._sizeGradients = [];
  57728. }
  57729. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57730. return this;
  57731. };
  57732. /**
  57733. * Remove a specific size gradient
  57734. * @param gradient defines the gradient to remove
  57735. * @returns the current particle system
  57736. */
  57737. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57738. this._removeFactorGradient(this._sizeGradients, gradient);
  57739. return this;
  57740. };
  57741. /**
  57742. * Adds a new color remap gradient
  57743. * @param gradient defines the gradient to use (between 0 and 1)
  57744. * @param min defines the color remap minimal range
  57745. * @param max defines the color remap maximal range
  57746. * @returns the current particle system
  57747. */
  57748. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57749. if (!this._colorRemapGradients) {
  57750. this._colorRemapGradients = [];
  57751. }
  57752. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57753. return this;
  57754. };
  57755. /**
  57756. * Remove a specific color remap gradient
  57757. * @param gradient defines the gradient to remove
  57758. * @returns the current particle system
  57759. */
  57760. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57761. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57762. return this;
  57763. };
  57764. /**
  57765. * Adds a new alpha remap gradient
  57766. * @param gradient defines the gradient to use (between 0 and 1)
  57767. * @param min defines the alpha remap minimal range
  57768. * @param max defines the alpha remap maximal range
  57769. * @returns the current particle system
  57770. */
  57771. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57772. if (!this._alphaRemapGradients) {
  57773. this._alphaRemapGradients = [];
  57774. }
  57775. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57776. return this;
  57777. };
  57778. /**
  57779. * Remove a specific alpha remap gradient
  57780. * @param gradient defines the gradient to remove
  57781. * @returns the current particle system
  57782. */
  57783. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57784. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57785. return this;
  57786. };
  57787. /**
  57788. * Adds a new angular speed gradient
  57789. * @param gradient defines the gradient to use (between 0 and 1)
  57790. * @param factor defines the angular speed to affect to the specified gradient
  57791. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57792. * @returns the current particle system
  57793. */
  57794. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57795. if (!this._angularSpeedGradients) {
  57796. this._angularSpeedGradients = [];
  57797. }
  57798. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57799. return this;
  57800. };
  57801. /**
  57802. * Remove a specific angular speed gradient
  57803. * @param gradient defines the gradient to remove
  57804. * @returns the current particle system
  57805. */
  57806. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57807. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57808. return this;
  57809. };
  57810. /**
  57811. * Adds a new velocity gradient
  57812. * @param gradient defines the gradient to use (between 0 and 1)
  57813. * @param factor defines the velocity to affect to the specified gradient
  57814. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57815. * @returns the current particle system
  57816. */
  57817. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57818. if (!this._velocityGradients) {
  57819. this._velocityGradients = [];
  57820. }
  57821. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57822. return this;
  57823. };
  57824. /**
  57825. * Remove a specific velocity gradient
  57826. * @param gradient defines the gradient to remove
  57827. * @returns the current particle system
  57828. */
  57829. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57830. this._removeFactorGradient(this._velocityGradients, gradient);
  57831. return this;
  57832. };
  57833. /**
  57834. * Adds a new limit velocity gradient
  57835. * @param gradient defines the gradient to use (between 0 and 1)
  57836. * @param factor defines the limit velocity value to affect to the specified gradient
  57837. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57838. * @returns the current particle system
  57839. */
  57840. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57841. if (!this._limitVelocityGradients) {
  57842. this._limitVelocityGradients = [];
  57843. }
  57844. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57845. return this;
  57846. };
  57847. /**
  57848. * Remove a specific limit velocity gradient
  57849. * @param gradient defines the gradient to remove
  57850. * @returns the current particle system
  57851. */
  57852. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57853. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57854. return this;
  57855. };
  57856. /**
  57857. * Adds a new drag gradient
  57858. * @param gradient defines the gradient to use (between 0 and 1)
  57859. * @param factor defines the drag value to affect to the specified gradient
  57860. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57861. * @returns the current particle system
  57862. */
  57863. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57864. if (!this._dragGradients) {
  57865. this._dragGradients = [];
  57866. }
  57867. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57868. return this;
  57869. };
  57870. /**
  57871. * Remove a specific drag gradient
  57872. * @param gradient defines the gradient to remove
  57873. * @returns the current particle system
  57874. */
  57875. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57876. this._removeFactorGradient(this._dragGradients, gradient);
  57877. return this;
  57878. };
  57879. /**
  57880. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57881. * @param gradient defines the gradient to use (between 0 and 1)
  57882. * @param factor defines the emit rate value to affect to the specified gradient
  57883. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57884. * @returns the current particle system
  57885. */
  57886. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57887. if (!this._emitRateGradients) {
  57888. this._emitRateGradients = [];
  57889. }
  57890. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57891. if (!this._currentEmitRateGradient) {
  57892. this._currentEmitRateGradient = this._emitRateGradients[0];
  57893. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57894. this._currentEmitRate2 = this._currentEmitRate1;
  57895. }
  57896. if (this._emitRateGradients.length === 2) {
  57897. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57898. }
  57899. return this;
  57900. };
  57901. /**
  57902. * Remove a specific emit rate gradient
  57903. * @param gradient defines the gradient to remove
  57904. * @returns the current particle system
  57905. */
  57906. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57907. this._removeFactorGradient(this._emitRateGradients, gradient);
  57908. return this;
  57909. };
  57910. /**
  57911. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57912. * @param gradient defines the gradient to use (between 0 and 1)
  57913. * @param factor defines the start size value to affect to the specified gradient
  57914. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57915. * @returns the current particle system
  57916. */
  57917. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57918. if (!this._startSizeGradients) {
  57919. this._startSizeGradients = [];
  57920. }
  57921. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57922. if (!this._currentStartSizeGradient) {
  57923. this._currentStartSizeGradient = this._startSizeGradients[0];
  57924. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57925. this._currentStartSize2 = this._currentStartSize1;
  57926. }
  57927. if (this._startSizeGradients.length === 2) {
  57928. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57929. }
  57930. return this;
  57931. };
  57932. /**
  57933. * Remove a specific start size gradient
  57934. * @param gradient defines the gradient to remove
  57935. * @returns the current particle system
  57936. */
  57937. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57938. this._removeFactorGradient(this._emitRateGradients, gradient);
  57939. return this;
  57940. };
  57941. ParticleSystem.prototype._createRampGradientTexture = function () {
  57942. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57943. return;
  57944. }
  57945. var data = new Uint8Array(this._rawTextureWidth * 4);
  57946. var tmpColor = BABYLON.Tmp.Color3[0];
  57947. for (var x = 0; x < this._rawTextureWidth; x++) {
  57948. var ratio = x / this._rawTextureWidth;
  57949. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57950. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57951. data[x * 4] = tmpColor.r * 255;
  57952. data[x * 4 + 1] = tmpColor.g * 255;
  57953. data[x * 4 + 2] = tmpColor.b * 255;
  57954. data[x * 4 + 3] = 255;
  57955. });
  57956. }
  57957. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57958. };
  57959. /**
  57960. * Gets the current list of ramp gradients.
  57961. * You must use addRampGradient and removeRampGradient to udpate this list
  57962. * @returns the list of ramp gradients
  57963. */
  57964. ParticleSystem.prototype.getRampGradients = function () {
  57965. return this._rampGradients;
  57966. };
  57967. /**
  57968. * Adds a new ramp gradient used to remap particle colors
  57969. * @param gradient defines the gradient to use (between 0 and 1)
  57970. * @param color defines the color to affect to the specified gradient
  57971. * @returns the current particle system
  57972. */
  57973. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  57974. if (!this._rampGradients) {
  57975. this._rampGradients = [];
  57976. }
  57977. var rampGradient = new BABYLON.Color3Gradient();
  57978. rampGradient.gradient = gradient;
  57979. rampGradient.color = color;
  57980. this._rampGradients.push(rampGradient);
  57981. this._rampGradients.sort(function (a, b) {
  57982. if (a.gradient < b.gradient) {
  57983. return -1;
  57984. }
  57985. else if (a.gradient > b.gradient) {
  57986. return 1;
  57987. }
  57988. return 0;
  57989. });
  57990. if (this._rampGradientsTexture) {
  57991. this._rampGradientsTexture.dispose();
  57992. this._rampGradientsTexture = null;
  57993. }
  57994. this._createRampGradientTexture();
  57995. return this;
  57996. };
  57997. /**
  57998. * Remove a specific ramp gradient
  57999. * @param gradient defines the gradient to remove
  58000. * @returns the current particle system
  58001. */
  58002. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58003. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58004. this._rampGradientsTexture = null;
  58005. if (this._rampGradients && this._rampGradients.length > 0) {
  58006. this._createRampGradientTexture();
  58007. }
  58008. return this;
  58009. };
  58010. /**
  58011. * Adds a new color gradient
  58012. * @param gradient defines the gradient to use (between 0 and 1)
  58013. * @param color1 defines the color to affect to the specified gradient
  58014. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58015. */
  58016. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58017. if (!this._colorGradients) {
  58018. this._colorGradients = [];
  58019. }
  58020. var colorGradient = new BABYLON.ColorGradient();
  58021. colorGradient.gradient = gradient;
  58022. colorGradient.color1 = color1;
  58023. colorGradient.color2 = color2;
  58024. this._colorGradients.push(colorGradient);
  58025. this._colorGradients.sort(function (a, b) {
  58026. if (a.gradient < b.gradient) {
  58027. return -1;
  58028. }
  58029. else if (a.gradient > b.gradient) {
  58030. return 1;
  58031. }
  58032. return 0;
  58033. });
  58034. return this;
  58035. };
  58036. /**
  58037. * Remove a specific color gradient
  58038. * @param gradient defines the gradient to remove
  58039. */
  58040. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58041. if (!this._colorGradients) {
  58042. return this;
  58043. }
  58044. var index = 0;
  58045. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58046. var colorGradient = _a[_i];
  58047. if (colorGradient.gradient === gradient) {
  58048. this._colorGradients.splice(index, 1);
  58049. break;
  58050. }
  58051. index++;
  58052. }
  58053. return this;
  58054. };
  58055. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58056. u = Math.abs(u) * 0.5 + 0.5;
  58057. v = Math.abs(v) * 0.5 + 0.5;
  58058. var wrappedU = ((u * width) % width) | 0;
  58059. var wrappedV = ((v * height) % height) | 0;
  58060. var position = (wrappedU + wrappedV * width) * 4;
  58061. return pixels[position] / 255;
  58062. };
  58063. ParticleSystem.prototype._reset = function () {
  58064. this._resetEffect();
  58065. };
  58066. ParticleSystem.prototype._resetEffect = function () {
  58067. if (this._vertexBuffer) {
  58068. this._vertexBuffer.dispose();
  58069. this._vertexBuffer = null;
  58070. }
  58071. if (this._spriteBuffer) {
  58072. this._spriteBuffer.dispose();
  58073. this._spriteBuffer = null;
  58074. }
  58075. this._createVertexBuffers();
  58076. };
  58077. ParticleSystem.prototype._createVertexBuffers = function () {
  58078. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58079. if (this._isAnimationSheetEnabled) {
  58080. this._vertexBufferSize += 1;
  58081. }
  58082. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58083. this._vertexBufferSize += 3;
  58084. }
  58085. if (this._useRampGradients) {
  58086. this._vertexBufferSize += 4;
  58087. }
  58088. var engine = this._scene.getEngine();
  58089. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58090. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58091. var dataOffset = 0;
  58092. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58094. dataOffset += 3;
  58095. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58096. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58097. dataOffset += 4;
  58098. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58099. this._vertexBuffers["angle"] = options;
  58100. dataOffset += 1;
  58101. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58102. this._vertexBuffers["size"] = size;
  58103. dataOffset += 2;
  58104. if (this._isAnimationSheetEnabled) {
  58105. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58106. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58107. dataOffset += 1;
  58108. }
  58109. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58110. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58111. this._vertexBuffers["direction"] = directionBuffer;
  58112. dataOffset += 3;
  58113. }
  58114. if (this._useRampGradients) {
  58115. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58116. this._vertexBuffers["remapData"] = rampDataBuffer;
  58117. dataOffset += 4;
  58118. }
  58119. var offsets;
  58120. if (this._useInstancing) {
  58121. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58122. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58123. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58124. }
  58125. else {
  58126. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58127. dataOffset += 2;
  58128. }
  58129. this._vertexBuffers["offset"] = offsets;
  58130. };
  58131. ParticleSystem.prototype._createIndexBuffer = function () {
  58132. if (this._useInstancing) {
  58133. return;
  58134. }
  58135. var indices = [];
  58136. var index = 0;
  58137. for (var count = 0; count < this._capacity; count++) {
  58138. indices.push(index);
  58139. indices.push(index + 1);
  58140. indices.push(index + 2);
  58141. indices.push(index);
  58142. indices.push(index + 2);
  58143. indices.push(index + 3);
  58144. index += 4;
  58145. }
  58146. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58147. };
  58148. /**
  58149. * Gets the maximum number of particles active at the same time.
  58150. * @returns The max number of active particles.
  58151. */
  58152. ParticleSystem.prototype.getCapacity = function () {
  58153. return this._capacity;
  58154. };
  58155. /**
  58156. * Gets whether there are still active particles in the system.
  58157. * @returns True if it is alive, otherwise false.
  58158. */
  58159. ParticleSystem.prototype.isAlive = function () {
  58160. return this._alive;
  58161. };
  58162. /**
  58163. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58164. * @returns True if it has been started, otherwise false.
  58165. */
  58166. ParticleSystem.prototype.isStarted = function () {
  58167. return this._started;
  58168. };
  58169. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58170. var _this = this;
  58171. this._subEmitters = new Array();
  58172. if (this.subEmitters) {
  58173. this.subEmitters.forEach(function (subEmitter) {
  58174. if (subEmitter instanceof ParticleSystem) {
  58175. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58176. }
  58177. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58178. _this._subEmitters.push([subEmitter]);
  58179. }
  58180. else if (subEmitter instanceof Array) {
  58181. _this._subEmitters.push(subEmitter);
  58182. }
  58183. });
  58184. }
  58185. };
  58186. /**
  58187. * Starts the particle system and begins to emit
  58188. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58189. */
  58190. ParticleSystem.prototype.start = function (delay) {
  58191. var _this = this;
  58192. if (delay === void 0) { delay = this.startDelay; }
  58193. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58194. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58195. }
  58196. if (delay) {
  58197. setTimeout(function () {
  58198. _this.start(0);
  58199. }, delay);
  58200. return;
  58201. }
  58202. // Convert the subEmitters field to the constant type field _subEmitters
  58203. this._prepareSubEmitterInternalArray();
  58204. this._started = true;
  58205. this._stopped = false;
  58206. this._actualFrame = 0;
  58207. if (this._subEmitters && this._subEmitters.length != 0) {
  58208. this.activeSubSystems = new Array();
  58209. }
  58210. if (this.preWarmCycles) {
  58211. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58212. this.emitter.computeWorldMatrix(true);
  58213. }
  58214. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58215. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58216. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58217. setTimeout(function () {
  58218. for (var index = 0; index < _this.preWarmCycles; index++) {
  58219. _this.animate(true);
  58220. noiseTextureAsProcedural_1.render();
  58221. }
  58222. });
  58223. });
  58224. }
  58225. else {
  58226. for (var index = 0; index < this.preWarmCycles; index++) {
  58227. this.animate(true);
  58228. }
  58229. }
  58230. }
  58231. // Animations
  58232. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58233. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58234. }
  58235. };
  58236. /**
  58237. * Stops the particle system.
  58238. * @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.
  58239. */
  58240. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58241. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58242. this._stopped = true;
  58243. if (stopSubEmitters) {
  58244. this._stopSubEmitters();
  58245. }
  58246. };
  58247. // animation sheet
  58248. /**
  58249. * Remove all active particles
  58250. */
  58251. ParticleSystem.prototype.reset = function () {
  58252. this._stockParticles = [];
  58253. this._particles = [];
  58254. };
  58255. /**
  58256. * @hidden (for internal use only)
  58257. */
  58258. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58259. var offset = index * this._vertexBufferSize;
  58260. this._vertexData[offset++] = particle.position.x;
  58261. this._vertexData[offset++] = particle.position.y;
  58262. this._vertexData[offset++] = particle.position.z;
  58263. this._vertexData[offset++] = particle.color.r;
  58264. this._vertexData[offset++] = particle.color.g;
  58265. this._vertexData[offset++] = particle.color.b;
  58266. this._vertexData[offset++] = particle.color.a;
  58267. this._vertexData[offset++] = particle.angle;
  58268. this._vertexData[offset++] = particle.scale.x * particle.size;
  58269. this._vertexData[offset++] = particle.scale.y * particle.size;
  58270. if (this._isAnimationSheetEnabled) {
  58271. this._vertexData[offset++] = particle.cellIndex;
  58272. }
  58273. if (!this._isBillboardBased) {
  58274. if (particle._initialDirection) {
  58275. this._vertexData[offset++] = particle._initialDirection.x;
  58276. this._vertexData[offset++] = particle._initialDirection.y;
  58277. this._vertexData[offset++] = particle._initialDirection.z;
  58278. }
  58279. else {
  58280. this._vertexData[offset++] = particle.direction.x;
  58281. this._vertexData[offset++] = particle.direction.y;
  58282. this._vertexData[offset++] = particle.direction.z;
  58283. }
  58284. }
  58285. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58286. this._vertexData[offset++] = particle.direction.x;
  58287. this._vertexData[offset++] = particle.direction.y;
  58288. this._vertexData[offset++] = particle.direction.z;
  58289. }
  58290. if (this._useRampGradients) {
  58291. this._vertexData[offset++] = particle.remapData.x;
  58292. this._vertexData[offset++] = particle.remapData.y;
  58293. this._vertexData[offset++] = particle.remapData.z;
  58294. this._vertexData[offset++] = particle.remapData.w;
  58295. }
  58296. if (!this._useInstancing) {
  58297. if (this._isAnimationSheetEnabled) {
  58298. if (offsetX === 0)
  58299. offsetX = this._epsilon;
  58300. else if (offsetX === 1)
  58301. offsetX = 1 - this._epsilon;
  58302. if (offsetY === 0)
  58303. offsetY = this._epsilon;
  58304. else if (offsetY === 1)
  58305. offsetY = 1 - this._epsilon;
  58306. }
  58307. this._vertexData[offset++] = offsetX;
  58308. this._vertexData[offset++] = offsetY;
  58309. }
  58310. };
  58311. ParticleSystem.prototype._stopSubEmitters = function () {
  58312. if (!this.activeSubSystems) {
  58313. return;
  58314. }
  58315. this.activeSubSystems.forEach(function (subSystem) {
  58316. subSystem.stop(true);
  58317. });
  58318. this.activeSubSystems = new Array();
  58319. };
  58320. ParticleSystem.prototype._removeFromRoot = function () {
  58321. if (!this._rootParticleSystem) {
  58322. return;
  58323. }
  58324. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58325. if (index !== -1) {
  58326. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58327. }
  58328. this._rootParticleSystem = null;
  58329. };
  58330. // End of sub system methods
  58331. ParticleSystem.prototype._update = function (newParticles) {
  58332. var _this = this;
  58333. // Update current
  58334. this._alive = this._particles.length > 0;
  58335. if (this.emitter.position) {
  58336. var emitterMesh = this.emitter;
  58337. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58338. }
  58339. else {
  58340. var emitterPosition = this.emitter;
  58341. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58342. }
  58343. this.updateFunction(this._particles);
  58344. // Add new ones
  58345. var particle;
  58346. var _loop_2 = function () {
  58347. if (this_1._particles.length === this_1._capacity) {
  58348. return "break";
  58349. }
  58350. particle = this_1._createParticle();
  58351. this_1._particles.push(particle);
  58352. // Emitter
  58353. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58354. if (this_1.startPositionFunction) {
  58355. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58356. }
  58357. else {
  58358. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58359. }
  58360. if (this_1.startDirectionFunction) {
  58361. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58362. }
  58363. else {
  58364. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58365. }
  58366. if (emitPower === 0) {
  58367. if (!particle._initialDirection) {
  58368. particle._initialDirection = particle.direction.clone();
  58369. }
  58370. else {
  58371. particle._initialDirection.copyFrom(particle.direction);
  58372. }
  58373. }
  58374. else {
  58375. particle._initialDirection = null;
  58376. }
  58377. particle.direction.scaleInPlace(emitPower);
  58378. // Life time
  58379. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58380. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58381. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58382. var factorGradient1 = currentGradient;
  58383. var factorGradient2 = nextGradient;
  58384. var lifeTime1 = factorGradient1.getFactor();
  58385. var lifeTime2 = factorGradient2.getFactor();
  58386. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58387. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58388. });
  58389. }
  58390. else {
  58391. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58392. }
  58393. // Size
  58394. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58395. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58396. }
  58397. else {
  58398. particle._currentSizeGradient = this_1._sizeGradients[0];
  58399. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58400. particle.size = particle._currentSize1;
  58401. if (this_1._sizeGradients.length > 1) {
  58402. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58403. }
  58404. else {
  58405. particle._currentSize2 = particle._currentSize1;
  58406. }
  58407. }
  58408. // Size and scale
  58409. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58410. // Adjust scale by start size
  58411. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58412. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58413. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58414. if (currentGradient !== _this._currentStartSizeGradient) {
  58415. _this._currentStartSize1 = _this._currentStartSize2;
  58416. _this._currentStartSize2 = nextGradient.getFactor();
  58417. _this._currentStartSizeGradient = currentGradient;
  58418. }
  58419. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58420. particle.scale.scaleInPlace(value);
  58421. });
  58422. }
  58423. // Angle
  58424. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58425. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58426. }
  58427. else {
  58428. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58429. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58430. particle._currentAngularSpeed1 = particle.angularSpeed;
  58431. if (this_1._angularSpeedGradients.length > 1) {
  58432. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58433. }
  58434. else {
  58435. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58436. }
  58437. }
  58438. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58439. // Velocity
  58440. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58441. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58442. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58443. if (this_1._velocityGradients.length > 1) {
  58444. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58445. }
  58446. else {
  58447. particle._currentVelocity2 = particle._currentVelocity1;
  58448. }
  58449. }
  58450. // Limit velocity
  58451. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58452. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58453. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58454. if (this_1._limitVelocityGradients.length > 1) {
  58455. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58456. }
  58457. else {
  58458. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58459. }
  58460. }
  58461. // Drag
  58462. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58463. particle._currentDragGradient = this_1._dragGradients[0];
  58464. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58465. if (this_1._dragGradients.length > 1) {
  58466. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58467. }
  58468. else {
  58469. particle._currentDrag2 = particle._currentDrag1;
  58470. }
  58471. }
  58472. // Color
  58473. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58474. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58475. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58476. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58477. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58478. }
  58479. else {
  58480. particle._currentColorGradient = this_1._colorGradients[0];
  58481. particle._currentColorGradient.getColorToRef(particle.color);
  58482. particle._currentColor1.copyFrom(particle.color);
  58483. if (this_1._colorGradients.length > 1) {
  58484. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58485. }
  58486. else {
  58487. particle._currentColor2.copyFrom(particle.color);
  58488. }
  58489. }
  58490. // Sheet
  58491. if (this_1._isAnimationSheetEnabled) {
  58492. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58493. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58494. }
  58495. // Inherited Velocity
  58496. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58497. // Ramp
  58498. if (this_1._useRampGradients) {
  58499. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58500. }
  58501. // Noise texture coordinates
  58502. if (this_1.noiseTexture) {
  58503. if (particle._randomNoiseCoordinates1) {
  58504. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58505. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58506. }
  58507. else {
  58508. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58509. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58510. }
  58511. }
  58512. // Update the position of the attached sub-emitters to match their attached particle
  58513. particle._inheritParticleInfoToSubEmitters();
  58514. };
  58515. var this_1 = this, step;
  58516. for (var index = 0; index < newParticles; index++) {
  58517. var state_1 = _loop_2();
  58518. if (state_1 === "break")
  58519. break;
  58520. }
  58521. };
  58522. /** @hidden */
  58523. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58524. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58525. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58526. if (useRampGradients === void 0) { useRampGradients = false; }
  58527. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58528. if (isAnimationSheetEnabled) {
  58529. attributeNamesOrOptions.push("cellIndex");
  58530. }
  58531. if (!isBillboardBased) {
  58532. attributeNamesOrOptions.push("direction");
  58533. }
  58534. if (useRampGradients) {
  58535. attributeNamesOrOptions.push("remapData");
  58536. }
  58537. return attributeNamesOrOptions;
  58538. };
  58539. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58540. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58541. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58542. if (isAnimationSheetEnabled) {
  58543. effectCreationOption.push("particlesInfos");
  58544. }
  58545. return effectCreationOption;
  58546. };
  58547. ParticleSystem.prototype._getEffect = function (blendMode) {
  58548. if (this._customEffect) {
  58549. return this._customEffect;
  58550. }
  58551. ;
  58552. var defines = [];
  58553. if (this._scene.clipPlane) {
  58554. defines.push("#define CLIPPLANE");
  58555. }
  58556. if (this._scene.clipPlane2) {
  58557. defines.push("#define CLIPPLANE2");
  58558. }
  58559. if (this._scene.clipPlane3) {
  58560. defines.push("#define CLIPPLANE3");
  58561. }
  58562. if (this._scene.clipPlane4) {
  58563. defines.push("#define CLIPPLANE4");
  58564. }
  58565. if (this._isAnimationSheetEnabled) {
  58566. defines.push("#define ANIMATESHEET");
  58567. }
  58568. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58569. defines.push("#define BLENDMULTIPLYMODE");
  58570. }
  58571. if (this._useRampGradients) {
  58572. defines.push("#define RAMPGRADIENT");
  58573. }
  58574. if (this._isBillboardBased) {
  58575. defines.push("#define BILLBOARD");
  58576. switch (this.billboardMode) {
  58577. case ParticleSystem.BILLBOARDMODE_Y:
  58578. defines.push("#define BILLBOARDY");
  58579. break;
  58580. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58581. defines.push("#define BILLBOARDSTRETCHED");
  58582. break;
  58583. case ParticleSystem.BILLBOARDMODE_ALL:
  58584. default:
  58585. break;
  58586. }
  58587. }
  58588. if (this._imageProcessingConfiguration) {
  58589. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58590. defines.push(this._imageProcessingConfigurationDefines.toString());
  58591. }
  58592. // Effect
  58593. var join = defines.join("\n");
  58594. if (this._cachedDefines !== join) {
  58595. this._cachedDefines = join;
  58596. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58597. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58598. var samplers = ["diffuseSampler", "rampSampler"];
  58599. if (BABYLON.ImageProcessingConfiguration) {
  58600. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58601. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58602. }
  58603. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58604. }
  58605. return this._effect;
  58606. };
  58607. /**
  58608. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58609. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58610. */
  58611. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58612. var _this = this;
  58613. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58614. if (!this._started)
  58615. return;
  58616. if (!preWarmOnly) {
  58617. // Check
  58618. if (!this.isReady())
  58619. return;
  58620. if (this._currentRenderId === this._scene.getRenderId()) {
  58621. return;
  58622. }
  58623. this._currentRenderId = this._scene.getRenderId();
  58624. }
  58625. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58626. // Determine the number of particles we need to create
  58627. var newParticles;
  58628. if (this.manualEmitCount > -1) {
  58629. newParticles = this.manualEmitCount;
  58630. this._newPartsExcess = 0;
  58631. this.manualEmitCount = 0;
  58632. }
  58633. else {
  58634. var rate_1 = this.emitRate;
  58635. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58636. var ratio = this._actualFrame / this.targetStopDuration;
  58637. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58638. if (currentGradient !== _this._currentEmitRateGradient) {
  58639. _this._currentEmitRate1 = _this._currentEmitRate2;
  58640. _this._currentEmitRate2 = nextGradient.getFactor();
  58641. _this._currentEmitRateGradient = currentGradient;
  58642. }
  58643. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58644. });
  58645. }
  58646. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58647. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58648. }
  58649. if (this._newPartsExcess > 1.0) {
  58650. newParticles += this._newPartsExcess >> 0;
  58651. this._newPartsExcess -= this._newPartsExcess >> 0;
  58652. }
  58653. this._alive = false;
  58654. if (!this._stopped) {
  58655. this._actualFrame += this._scaledUpdateSpeed;
  58656. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58657. this.stop();
  58658. }
  58659. else {
  58660. newParticles = 0;
  58661. }
  58662. this._update(newParticles);
  58663. // Stopped?
  58664. if (this._stopped) {
  58665. if (!this._alive) {
  58666. this._started = false;
  58667. if (this.onAnimationEnd) {
  58668. this.onAnimationEnd();
  58669. }
  58670. if (this.disposeOnStop) {
  58671. this._scene._toBeDisposed.push(this);
  58672. }
  58673. }
  58674. }
  58675. if (!preWarmOnly) {
  58676. // Update VBO
  58677. var offset = 0;
  58678. for (var index = 0; index < this._particles.length; index++) {
  58679. var particle = this._particles[index];
  58680. this._appendParticleVertices(offset, particle);
  58681. offset += this._useInstancing ? 1 : 4;
  58682. }
  58683. if (this._vertexBuffer) {
  58684. this._vertexBuffer.update(this._vertexData);
  58685. }
  58686. }
  58687. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58688. this.stop();
  58689. }
  58690. };
  58691. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58692. this._appendParticleVertex(offset++, particle, 0, 0);
  58693. if (!this._useInstancing) {
  58694. this._appendParticleVertex(offset++, particle, 1, 0);
  58695. this._appendParticleVertex(offset++, particle, 1, 1);
  58696. this._appendParticleVertex(offset++, particle, 0, 1);
  58697. }
  58698. };
  58699. /**
  58700. * Rebuilds the particle system.
  58701. */
  58702. ParticleSystem.prototype.rebuild = function () {
  58703. this._createIndexBuffer();
  58704. if (this._vertexBuffer) {
  58705. this._vertexBuffer._rebuild();
  58706. }
  58707. };
  58708. /**
  58709. * Is this system ready to be used/rendered
  58710. * @return true if the system is ready
  58711. */
  58712. ParticleSystem.prototype.isReady = function () {
  58713. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58714. return false;
  58715. }
  58716. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58717. if (!this._getEffect(this.blendMode).isReady()) {
  58718. return false;
  58719. }
  58720. }
  58721. else {
  58722. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58723. return false;
  58724. }
  58725. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58726. return false;
  58727. }
  58728. }
  58729. return true;
  58730. };
  58731. ParticleSystem.prototype._render = function (blendMode) {
  58732. var effect = this._getEffect(blendMode);
  58733. var engine = this._scene.getEngine();
  58734. // Render
  58735. engine.enableEffect(effect);
  58736. var viewMatrix = this._scene.getViewMatrix();
  58737. effect.setTexture("diffuseSampler", this.particleTexture);
  58738. effect.setMatrix("view", viewMatrix);
  58739. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58740. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58741. var baseSize = this.particleTexture.getBaseSize();
  58742. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58743. }
  58744. effect.setVector2("translationPivot", this.translationPivot);
  58745. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58746. if (this._isBillboardBased) {
  58747. var camera = this._scene.activeCamera;
  58748. effect.setVector3("eyePosition", camera.globalPosition);
  58749. }
  58750. if (this._rampGradientsTexture) {
  58751. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58752. }
  58753. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58754. var invView = viewMatrix.clone();
  58755. invView.invert();
  58756. effect.setMatrix("invView", invView);
  58757. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58758. }
  58759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58760. // image processing
  58761. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58762. this._imageProcessingConfiguration.bind(effect);
  58763. }
  58764. // Draw order
  58765. switch (blendMode) {
  58766. case ParticleSystem.BLENDMODE_ADD:
  58767. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58768. break;
  58769. case ParticleSystem.BLENDMODE_ONEONE:
  58770. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58771. break;
  58772. case ParticleSystem.BLENDMODE_STANDARD:
  58773. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58774. break;
  58775. case ParticleSystem.BLENDMODE_MULTIPLY:
  58776. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58777. break;
  58778. }
  58779. if (this._useInstancing) {
  58780. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58781. }
  58782. else {
  58783. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58784. }
  58785. return this._particles.length;
  58786. };
  58787. /**
  58788. * Renders the particle system in its current state.
  58789. * @returns the current number of particles
  58790. */
  58791. ParticleSystem.prototype.render = function () {
  58792. // Check
  58793. if (!this.isReady() || !this._particles.length) {
  58794. return 0;
  58795. }
  58796. var engine = this._scene.getEngine();
  58797. engine.setState(false);
  58798. if (this.forceDepthWrite) {
  58799. engine.setDepthWrite(true);
  58800. }
  58801. var outparticles = 0;
  58802. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58803. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58804. }
  58805. outparticles = this._render(this.blendMode);
  58806. engine.unbindInstanceAttributes();
  58807. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58808. return outparticles;
  58809. };
  58810. /**
  58811. * Disposes the particle system and free the associated resources
  58812. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58813. */
  58814. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58815. if (disposeTexture === void 0) { disposeTexture = true; }
  58816. if (this._vertexBuffer) {
  58817. this._vertexBuffer.dispose();
  58818. this._vertexBuffer = null;
  58819. }
  58820. if (this._spriteBuffer) {
  58821. this._spriteBuffer.dispose();
  58822. this._spriteBuffer = null;
  58823. }
  58824. if (this._indexBuffer) {
  58825. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58826. this._indexBuffer = null;
  58827. }
  58828. if (disposeTexture && this.particleTexture) {
  58829. this.particleTexture.dispose();
  58830. this.particleTexture = null;
  58831. }
  58832. if (disposeTexture && this.noiseTexture) {
  58833. this.noiseTexture.dispose();
  58834. this.noiseTexture = null;
  58835. }
  58836. if (this._rampGradientsTexture) {
  58837. this._rampGradientsTexture.dispose();
  58838. this._rampGradientsTexture = null;
  58839. }
  58840. this._removeFromRoot();
  58841. if (this._subEmitters && this._subEmitters.length) {
  58842. for (var index = 0; index < this._subEmitters.length; index++) {
  58843. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58844. var subEmitter = _a[_i];
  58845. subEmitter.dispose();
  58846. }
  58847. }
  58848. this._subEmitters = [];
  58849. this.subEmitters = [];
  58850. }
  58851. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58852. this.emitter.dispose(true);
  58853. }
  58854. // Remove from scene
  58855. var index = this._scene.particleSystems.indexOf(this);
  58856. if (index > -1) {
  58857. this._scene.particleSystems.splice(index, 1);
  58858. }
  58859. this._scene._activeParticleSystems.dispose();
  58860. // Callback
  58861. this.onDisposeObservable.notifyObservers(this);
  58862. this.onDisposeObservable.clear();
  58863. this.reset();
  58864. };
  58865. // Clone
  58866. /**
  58867. * Clones the particle system.
  58868. * @param name The name of the cloned object
  58869. * @param newEmitter The new emitter to use
  58870. * @returns the cloned particle system
  58871. */
  58872. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58873. var custom = null;
  58874. var program = null;
  58875. if (this.customShader != null) {
  58876. program = this.customShader;
  58877. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58878. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58879. }
  58880. else if (this._customEffect) {
  58881. custom = this._customEffect;
  58882. }
  58883. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58884. result.customShader = program;
  58885. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58886. if (newEmitter === undefined) {
  58887. newEmitter = this.emitter;
  58888. }
  58889. result.noiseTexture = this.noiseTexture;
  58890. result.emitter = newEmitter;
  58891. if (this.particleTexture) {
  58892. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58893. }
  58894. // Clone gradients
  58895. if (this._colorGradients) {
  58896. this._colorGradients.forEach(function (v) {
  58897. result.addColorGradient(v.gradient, v.color1, v.color2);
  58898. });
  58899. }
  58900. if (this._dragGradients) {
  58901. this._dragGradients.forEach(function (v) {
  58902. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58903. });
  58904. }
  58905. if (this._angularSpeedGradients) {
  58906. this._angularSpeedGradients.forEach(function (v) {
  58907. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58908. });
  58909. }
  58910. if (this._emitRateGradients) {
  58911. this._emitRateGradients.forEach(function (v) {
  58912. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58913. });
  58914. }
  58915. if (this._lifeTimeGradients) {
  58916. this._lifeTimeGradients.forEach(function (v) {
  58917. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58918. });
  58919. }
  58920. if (this._limitVelocityGradients) {
  58921. this._limitVelocityGradients.forEach(function (v) {
  58922. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58923. });
  58924. }
  58925. if (this._sizeGradients) {
  58926. this._sizeGradients.forEach(function (v) {
  58927. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58928. });
  58929. }
  58930. if (this._startSizeGradients) {
  58931. this._startSizeGradients.forEach(function (v) {
  58932. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58933. });
  58934. }
  58935. if (this._velocityGradients) {
  58936. this._velocityGradients.forEach(function (v) {
  58937. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58938. });
  58939. }
  58940. if (this._rampGradients) {
  58941. this._rampGradients.forEach(function (v) {
  58942. result.addRampGradient(v.gradient, v.color);
  58943. });
  58944. }
  58945. if (this._colorRemapGradients) {
  58946. this._colorRemapGradients.forEach(function (v) {
  58947. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58948. });
  58949. }
  58950. if (this._alphaRemapGradients) {
  58951. this._alphaRemapGradients.forEach(function (v) {
  58952. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58953. });
  58954. }
  58955. if (!this.preventAutoStart) {
  58956. result.start();
  58957. }
  58958. return result;
  58959. };
  58960. /**
  58961. * Serializes the particle system to a JSON object.
  58962. * @returns the JSON object
  58963. */
  58964. ParticleSystem.prototype.serialize = function () {
  58965. var serializationObject = {};
  58966. ParticleSystem._Serialize(serializationObject, this);
  58967. serializationObject.textureMask = this.textureMask.asArray();
  58968. serializationObject.customShader = this.customShader;
  58969. serializationObject.preventAutoStart = this.preventAutoStart;
  58970. // SubEmitters
  58971. if (this.subEmitters) {
  58972. serializationObject.subEmitters = [];
  58973. if (!this._subEmitters) {
  58974. this._prepareSubEmitterInternalArray();
  58975. }
  58976. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  58977. var subs = _a[_i];
  58978. var cell = [];
  58979. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  58980. var sub = subs_1[_b];
  58981. cell.push(sub.serialize());
  58982. }
  58983. serializationObject.subEmitters.push(cell);
  58984. }
  58985. }
  58986. return serializationObject;
  58987. };
  58988. /** @hidden */
  58989. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  58990. serializationObject.name = particleSystem.name;
  58991. serializationObject.id = particleSystem.id;
  58992. serializationObject.capacity = particleSystem.getCapacity();
  58993. // Emitter
  58994. if (particleSystem.emitter.position) {
  58995. var emitterMesh = particleSystem.emitter;
  58996. serializationObject.emitterId = emitterMesh.id;
  58997. }
  58998. else {
  58999. var emitterPosition = particleSystem.emitter;
  59000. serializationObject.emitter = emitterPosition.asArray();
  59001. }
  59002. // Emitter
  59003. if (particleSystem.particleEmitterType) {
  59004. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59005. }
  59006. if (particleSystem.particleTexture) {
  59007. serializationObject.textureName = particleSystem.particleTexture.name;
  59008. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59009. }
  59010. // Animations
  59011. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59012. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59013. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59014. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59015. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59016. // Particle system
  59017. serializationObject.startDelay = particleSystem.startDelay;
  59018. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59019. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59020. serializationObject.billboardMode = particleSystem.billboardMode;
  59021. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59022. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59023. serializationObject.minSize = particleSystem.minSize;
  59024. serializationObject.maxSize = particleSystem.maxSize;
  59025. serializationObject.minScaleX = particleSystem.minScaleX;
  59026. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59027. serializationObject.minScaleY = particleSystem.minScaleY;
  59028. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59029. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59030. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59031. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59032. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59033. serializationObject.emitRate = particleSystem.emitRate;
  59034. serializationObject.gravity = particleSystem.gravity.asArray();
  59035. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59036. serializationObject.color1 = particleSystem.color1.asArray();
  59037. serializationObject.color2 = particleSystem.color2.asArray();
  59038. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59039. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59040. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59041. serializationObject.blendMode = particleSystem.blendMode;
  59042. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59043. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59044. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59045. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59046. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59047. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59048. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59049. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59050. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59051. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59052. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59053. var colorGradients = particleSystem.getColorGradients();
  59054. if (colorGradients) {
  59055. serializationObject.colorGradients = [];
  59056. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59057. var colorGradient = colorGradients_1[_i];
  59058. var serializedGradient = {
  59059. gradient: colorGradient.gradient,
  59060. color1: colorGradient.color1.asArray()
  59061. };
  59062. if (colorGradient.color2) {
  59063. serializedGradient.color2 = colorGradient.color2.asArray();
  59064. }
  59065. serializationObject.colorGradients.push(serializedGradient);
  59066. }
  59067. }
  59068. var rampGradients = particleSystem.getRampGradients();
  59069. if (rampGradients) {
  59070. serializationObject.rampGradients = [];
  59071. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59072. var rampGradient = rampGradients_1[_a];
  59073. var serializedGradient = {
  59074. gradient: rampGradient.gradient,
  59075. color: rampGradient.color.asArray()
  59076. };
  59077. serializationObject.rampGradients.push(serializedGradient);
  59078. }
  59079. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59080. }
  59081. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59082. if (colorRemapGradients) {
  59083. serializationObject.colorRemapGradients = [];
  59084. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59085. var colorRemapGradient = colorRemapGradients_1[_b];
  59086. var serializedGradient = {
  59087. gradient: colorRemapGradient.gradient,
  59088. factor1: colorRemapGradient.factor1
  59089. };
  59090. if (colorRemapGradient.factor2 !== undefined) {
  59091. serializedGradient.factor2 = colorRemapGradient.factor2;
  59092. }
  59093. serializationObject.colorRemapGradients.push(serializedGradient);
  59094. }
  59095. }
  59096. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59097. if (alphaRemapGradients) {
  59098. serializationObject.alphaRemapGradients = [];
  59099. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59100. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59101. var serializedGradient = {
  59102. gradient: alphaRemapGradient.gradient,
  59103. factor1: alphaRemapGradient.factor1
  59104. };
  59105. if (alphaRemapGradient.factor2 !== undefined) {
  59106. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59107. }
  59108. serializationObject.alphaRemapGradients.push(serializedGradient);
  59109. }
  59110. }
  59111. var sizeGradients = particleSystem.getSizeGradients();
  59112. if (sizeGradients) {
  59113. serializationObject.sizeGradients = [];
  59114. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59115. var sizeGradient = sizeGradients_1[_d];
  59116. var serializedGradient = {
  59117. gradient: sizeGradient.gradient,
  59118. factor1: sizeGradient.factor1
  59119. };
  59120. if (sizeGradient.factor2 !== undefined) {
  59121. serializedGradient.factor2 = sizeGradient.factor2;
  59122. }
  59123. serializationObject.sizeGradients.push(serializedGradient);
  59124. }
  59125. }
  59126. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59127. if (angularSpeedGradients) {
  59128. serializationObject.angularSpeedGradients = [];
  59129. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59130. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59131. var serializedGradient = {
  59132. gradient: angularSpeedGradient.gradient,
  59133. factor1: angularSpeedGradient.factor1
  59134. };
  59135. if (angularSpeedGradient.factor2 !== undefined) {
  59136. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59137. }
  59138. serializationObject.angularSpeedGradients.push(serializedGradient);
  59139. }
  59140. }
  59141. var velocityGradients = particleSystem.getVelocityGradients();
  59142. if (velocityGradients) {
  59143. serializationObject.velocityGradients = [];
  59144. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59145. var velocityGradient = velocityGradients_1[_f];
  59146. var serializedGradient = {
  59147. gradient: velocityGradient.gradient,
  59148. factor1: velocityGradient.factor1
  59149. };
  59150. if (velocityGradient.factor2 !== undefined) {
  59151. serializedGradient.factor2 = velocityGradient.factor2;
  59152. }
  59153. serializationObject.velocityGradients.push(serializedGradient);
  59154. }
  59155. }
  59156. var dragGradients = particleSystem.getDragGradients();
  59157. if (dragGradients) {
  59158. serializationObject.dragyGradients = [];
  59159. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59160. var dragGradient = dragGradients_1[_g];
  59161. var serializedGradient = {
  59162. gradient: dragGradient.gradient,
  59163. factor1: dragGradient.factor1
  59164. };
  59165. if (dragGradient.factor2 !== undefined) {
  59166. serializedGradient.factor2 = dragGradient.factor2;
  59167. }
  59168. serializationObject.dragGradients.push(serializedGradient);
  59169. }
  59170. }
  59171. var emitRateGradients = particleSystem.getEmitRateGradients();
  59172. if (emitRateGradients) {
  59173. serializationObject.emitRateGradients = [];
  59174. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59175. var emitRateGradient = emitRateGradients_1[_h];
  59176. var serializedGradient = {
  59177. gradient: emitRateGradient.gradient,
  59178. factor1: emitRateGradient.factor1
  59179. };
  59180. if (emitRateGradient.factor2 !== undefined) {
  59181. serializedGradient.factor2 = emitRateGradient.factor2;
  59182. }
  59183. serializationObject.emitRateGradients.push(serializedGradient);
  59184. }
  59185. }
  59186. var startSizeGradients = particleSystem.getStartSizeGradients();
  59187. if (startSizeGradients) {
  59188. serializationObject.startSizeGradients = [];
  59189. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59190. var startSizeGradient = startSizeGradients_1[_j];
  59191. var serializedGradient = {
  59192. gradient: startSizeGradient.gradient,
  59193. factor1: startSizeGradient.factor1
  59194. };
  59195. if (startSizeGradient.factor2 !== undefined) {
  59196. serializedGradient.factor2 = startSizeGradient.factor2;
  59197. }
  59198. serializationObject.startSizeGradients.push(serializedGradient);
  59199. }
  59200. }
  59201. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59202. if (lifeTimeGradients) {
  59203. serializationObject.lifeTimeGradients = [];
  59204. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59205. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59206. var serializedGradient = {
  59207. gradient: lifeTimeGradient.gradient,
  59208. factor1: lifeTimeGradient.factor1
  59209. };
  59210. if (lifeTimeGradient.factor2 !== undefined) {
  59211. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59212. }
  59213. serializationObject.lifeTimeGradients.push(serializedGradient);
  59214. }
  59215. }
  59216. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59217. if (limitVelocityGradients) {
  59218. serializationObject.limitVelocityGradients = [];
  59219. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59220. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59221. var serializedGradient = {
  59222. gradient: limitVelocityGradient.gradient,
  59223. factor1: limitVelocityGradient.factor1
  59224. };
  59225. if (limitVelocityGradient.factor2 !== undefined) {
  59226. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59227. }
  59228. serializationObject.limitVelocityGradients.push(serializedGradient);
  59229. }
  59230. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59231. }
  59232. if (particleSystem.noiseTexture) {
  59233. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59234. }
  59235. };
  59236. /** @hidden */
  59237. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59238. // Texture
  59239. if (parsedParticleSystem.textureName) {
  59240. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59241. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59242. }
  59243. // Emitter
  59244. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59245. particleSystem.emitter = BABYLON.Vector3.Zero();
  59246. }
  59247. else if (parsedParticleSystem.emitterId) {
  59248. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59249. }
  59250. else {
  59251. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59252. }
  59253. // Misc.
  59254. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59255. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59256. }
  59257. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59258. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59259. }
  59260. if (parsedParticleSystem.billboardMode !== undefined) {
  59261. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59262. }
  59263. // Animations
  59264. if (parsedParticleSystem.animations) {
  59265. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59266. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59267. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59268. }
  59269. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  59270. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  59271. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  59272. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  59273. }
  59274. if (parsedParticleSystem.autoAnimate) {
  59275. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59276. }
  59277. // Particle system
  59278. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59279. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59280. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59281. particleSystem.minSize = parsedParticleSystem.minSize;
  59282. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59283. if (parsedParticleSystem.minScaleX) {
  59284. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59285. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59286. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59287. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59288. }
  59289. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59290. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59291. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59292. }
  59293. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59294. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59295. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59296. }
  59297. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59298. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59299. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59300. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59301. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59302. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59303. if (parsedParticleSystem.noiseStrength) {
  59304. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59305. }
  59306. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59307. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59308. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59309. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59310. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59311. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59312. if (parsedParticleSystem.colorGradients) {
  59313. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59314. var colorGradient = _a[_i];
  59315. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59316. }
  59317. }
  59318. if (parsedParticleSystem.rampGradients) {
  59319. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59320. var rampGradient = _c[_b];
  59321. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59322. }
  59323. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59324. }
  59325. if (parsedParticleSystem.colorRemapGradients) {
  59326. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59327. var colorRemapGradient = _e[_d];
  59328. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59329. }
  59330. }
  59331. if (parsedParticleSystem.alphaRemapGradients) {
  59332. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59333. var alphaRemapGradient = _g[_f];
  59334. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59335. }
  59336. }
  59337. if (parsedParticleSystem.sizeGradients) {
  59338. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59339. var sizeGradient = _j[_h];
  59340. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59341. }
  59342. }
  59343. if (parsedParticleSystem.sizeGradients) {
  59344. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59345. var sizeGradient = _l[_k];
  59346. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59347. }
  59348. }
  59349. if (parsedParticleSystem.angularSpeedGradients) {
  59350. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59351. var angularSpeedGradient = _o[_m];
  59352. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59353. }
  59354. }
  59355. if (parsedParticleSystem.velocityGradients) {
  59356. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59357. var velocityGradient = _q[_p];
  59358. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59359. }
  59360. }
  59361. if (parsedParticleSystem.dragGradients) {
  59362. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59363. var dragGradient = _s[_r];
  59364. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59365. }
  59366. }
  59367. if (parsedParticleSystem.emitRateGradients) {
  59368. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59369. var emitRateGradient = _u[_t];
  59370. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59371. }
  59372. }
  59373. if (parsedParticleSystem.startSizeGradients) {
  59374. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59375. var startSizeGradient = _w[_v];
  59376. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59377. }
  59378. }
  59379. if (parsedParticleSystem.lifeTimeGradients) {
  59380. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  59381. var lifeTimeGradient = _y[_x];
  59382. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  59383. }
  59384. }
  59385. if (parsedParticleSystem.limitVelocityGradients) {
  59386. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  59387. var limitVelocityGradient = _0[_z];
  59388. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59389. }
  59390. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59391. }
  59392. if (parsedParticleSystem.noiseTexture) {
  59393. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59394. }
  59395. // Emitter
  59396. var emitterType;
  59397. if (parsedParticleSystem.particleEmitterType) {
  59398. switch (parsedParticleSystem.particleEmitterType.type) {
  59399. case "SphereParticleEmitter":
  59400. emitterType = new BABYLON.SphereParticleEmitter();
  59401. break;
  59402. case "SphereDirectedParticleEmitter":
  59403. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59404. break;
  59405. case "ConeEmitter":
  59406. case "ConeParticleEmitter":
  59407. emitterType = new BABYLON.ConeParticleEmitter();
  59408. break;
  59409. case "CylinderParticleEmitter":
  59410. emitterType = new BABYLON.CylinderParticleEmitter();
  59411. break;
  59412. case "HemisphericParticleEmitter":
  59413. emitterType = new BABYLON.HemisphericParticleEmitter();
  59414. break;
  59415. case "BoxEmitter":
  59416. case "BoxParticleEmitter":
  59417. default:
  59418. emitterType = new BABYLON.BoxParticleEmitter();
  59419. break;
  59420. }
  59421. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59422. }
  59423. else {
  59424. emitterType = new BABYLON.BoxParticleEmitter();
  59425. emitterType.parse(parsedParticleSystem);
  59426. }
  59427. particleSystem.particleEmitterType = emitterType;
  59428. // Animation sheet
  59429. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59430. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59431. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59432. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59433. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59434. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59435. };
  59436. /**
  59437. * Parses a JSON object to create a particle system.
  59438. * @param parsedParticleSystem The JSON object to parse
  59439. * @param scene The scene to create the particle system in
  59440. * @param rootUrl The root url to use to load external dependencies like texture
  59441. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  59442. * @returns the Parsed particle system
  59443. */
  59444. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  59445. if (doNotStart === void 0) { doNotStart = false; }
  59446. var name = parsedParticleSystem.name;
  59447. var custom = null;
  59448. var program = null;
  59449. if (parsedParticleSystem.customShader) {
  59450. program = parsedParticleSystem.customShader;
  59451. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59452. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59453. }
  59454. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59455. particleSystem.customShader = program;
  59456. if (parsedParticleSystem.id) {
  59457. particleSystem.id = parsedParticleSystem.id;
  59458. }
  59459. // SubEmitters
  59460. if (parsedParticleSystem.subEmitters) {
  59461. particleSystem.subEmitters = [];
  59462. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59463. var cell = _a[_i];
  59464. var cellArray = [];
  59465. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59466. var sub = cell_1[_b];
  59467. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59468. }
  59469. particleSystem.subEmitters.push(cellArray);
  59470. }
  59471. }
  59472. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59473. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59474. // Auto start
  59475. if (parsedParticleSystem.preventAutoStart) {
  59476. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59477. }
  59478. if (!doNotStart && !particleSystem.preventAutoStart) {
  59479. particleSystem.start();
  59480. }
  59481. return particleSystem;
  59482. };
  59483. /**
  59484. * Billboard mode will only apply to Y axis
  59485. */
  59486. ParticleSystem.BILLBOARDMODE_Y = 2;
  59487. /**
  59488. * Billboard mode will apply to all axes
  59489. */
  59490. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59491. /**
  59492. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59493. */
  59494. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59495. return ParticleSystem;
  59496. }(BABYLON.BaseParticleSystem));
  59497. BABYLON.ParticleSystem = ParticleSystem;
  59498. })(BABYLON || (BABYLON = {}));
  59499. //# sourceMappingURL=babylon.particleSystem.js.map
  59500. var BABYLON;
  59501. (function (BABYLON) {
  59502. /**
  59503. * Particle emitter emitting particles from the inside of a box.
  59504. * It emits the particles randomly between 2 given directions.
  59505. */
  59506. var BoxParticleEmitter = /** @class */ (function () {
  59507. /**
  59508. * Creates a new instance BoxParticleEmitter
  59509. */
  59510. function BoxParticleEmitter() {
  59511. /**
  59512. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59513. */
  59514. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59515. /**
  59516. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59517. */
  59518. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59519. /**
  59520. * 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.
  59521. */
  59522. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59523. /**
  59524. * 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.
  59525. */
  59526. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59527. }
  59528. /**
  59529. * Called by the particle System when the direction is computed for the created particle.
  59530. * @param worldMatrix is the world matrix of the particle system
  59531. * @param directionToUpdate is the direction vector to update with the result
  59532. * @param particle is the particle we are computed the direction for
  59533. */
  59534. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59535. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59536. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59537. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59538. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59539. };
  59540. /**
  59541. * Called by the particle System when the position is computed for the created particle.
  59542. * @param worldMatrix is the world matrix of the particle system
  59543. * @param positionToUpdate is the position vector to update with the result
  59544. * @param particle is the particle we are computed the position for
  59545. */
  59546. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59547. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59548. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59549. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59550. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59551. };
  59552. /**
  59553. * Clones the current emitter and returns a copy of it
  59554. * @returns the new emitter
  59555. */
  59556. BoxParticleEmitter.prototype.clone = function () {
  59557. var newOne = new BoxParticleEmitter();
  59558. BABYLON.Tools.DeepCopy(this, newOne);
  59559. return newOne;
  59560. };
  59561. /**
  59562. * Called by the GPUParticleSystem to setup the update shader
  59563. * @param effect defines the update shader
  59564. */
  59565. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59566. effect.setVector3("direction1", this.direction1);
  59567. effect.setVector3("direction2", this.direction2);
  59568. effect.setVector3("minEmitBox", this.minEmitBox);
  59569. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59570. };
  59571. /**
  59572. * Returns a string to use to update the GPU particles update shader
  59573. * @returns a string containng the defines string
  59574. */
  59575. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59576. return "#define BOXEMITTER";
  59577. };
  59578. /**
  59579. * Returns the string "BoxParticleEmitter"
  59580. * @returns a string containing the class name
  59581. */
  59582. BoxParticleEmitter.prototype.getClassName = function () {
  59583. return "BoxParticleEmitter";
  59584. };
  59585. /**
  59586. * Serializes the particle system to a JSON object.
  59587. * @returns the JSON object
  59588. */
  59589. BoxParticleEmitter.prototype.serialize = function () {
  59590. var serializationObject = {};
  59591. serializationObject.type = this.getClassName();
  59592. serializationObject.direction1 = this.direction1.asArray();
  59593. serializationObject.direction2 = this.direction2.asArray();
  59594. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59595. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59596. return serializationObject;
  59597. };
  59598. /**
  59599. * Parse properties from a JSON object
  59600. * @param serializationObject defines the JSON object
  59601. */
  59602. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59603. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59604. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59605. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59606. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59607. };
  59608. return BoxParticleEmitter;
  59609. }());
  59610. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59611. })(BABYLON || (BABYLON = {}));
  59612. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59613. var BABYLON;
  59614. (function (BABYLON) {
  59615. /**
  59616. * Particle emitter emitting particles from the inside of a cylinder.
  59617. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59618. */
  59619. var CylinderParticleEmitter = /** @class */ (function () {
  59620. /**
  59621. * Creates a new instance CylinderParticleEmitter
  59622. * @param radius the radius of the emission cylinder (1 by default)
  59623. * @param height the height of the emission cylinder (1 by default)
  59624. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59625. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59626. */
  59627. function CylinderParticleEmitter(
  59628. /**
  59629. * The radius of the emission cylinder.
  59630. */
  59631. radius,
  59632. /**
  59633. * The height of the emission cylinder.
  59634. */
  59635. height,
  59636. /**
  59637. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59638. */
  59639. radiusRange,
  59640. /**
  59641. * How much to randomize the particle direction [0-1].
  59642. */
  59643. directionRandomizer) {
  59644. if (radius === void 0) { radius = 1; }
  59645. if (height === void 0) { height = 1; }
  59646. if (radiusRange === void 0) { radiusRange = 1; }
  59647. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59648. this.radius = radius;
  59649. this.height = height;
  59650. this.radiusRange = radiusRange;
  59651. this.directionRandomizer = directionRandomizer;
  59652. }
  59653. /**
  59654. * Called by the particle System when the direction is computed for the created particle.
  59655. * @param worldMatrix is the world matrix of the particle system
  59656. * @param directionToUpdate is the direction vector to update with the result
  59657. * @param particle is the particle we are computed the direction for
  59658. */
  59659. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59660. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59661. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59662. var angle = Math.atan2(direction.x, direction.z);
  59663. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59664. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59665. direction.x = Math.sin(angle);
  59666. direction.z = Math.cos(angle);
  59667. direction.normalize();
  59668. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59669. };
  59670. /**
  59671. * Called by the particle System when the position is computed for the created particle.
  59672. * @param worldMatrix is the world matrix of the particle system
  59673. * @param positionToUpdate is the position vector to update with the result
  59674. * @param particle is the particle we are computed the position for
  59675. */
  59676. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59677. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59678. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59679. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59680. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59681. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59682. var xPos = positionRadius * Math.cos(angle);
  59683. var zPos = positionRadius * Math.sin(angle);
  59684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59685. };
  59686. /**
  59687. * Clones the current emitter and returns a copy of it
  59688. * @returns the new emitter
  59689. */
  59690. CylinderParticleEmitter.prototype.clone = function () {
  59691. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59692. BABYLON.Tools.DeepCopy(this, newOne);
  59693. return newOne;
  59694. };
  59695. /**
  59696. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59697. * @param effect defines the update shader
  59698. */
  59699. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59700. effect.setFloat("radius", this.radius);
  59701. effect.setFloat("height", this.height);
  59702. effect.setFloat("radiusRange", this.radiusRange);
  59703. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59704. };
  59705. /**
  59706. * Returns a string to use to update the GPU particles update shader
  59707. * @returns a string containng the defines string
  59708. */
  59709. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59710. return "#define CYLINDEREMITTER";
  59711. };
  59712. /**
  59713. * Returns the string "CylinderParticleEmitter"
  59714. * @returns a string containing the class name
  59715. */
  59716. CylinderParticleEmitter.prototype.getClassName = function () {
  59717. return "CylinderParticleEmitter";
  59718. };
  59719. /**
  59720. * Serializes the particle system to a JSON object.
  59721. * @returns the JSON object
  59722. */
  59723. CylinderParticleEmitter.prototype.serialize = function () {
  59724. var serializationObject = {};
  59725. serializationObject.type = this.getClassName();
  59726. serializationObject.radius = this.radius;
  59727. serializationObject.height = this.height;
  59728. serializationObject.radiusRange = this.radiusRange;
  59729. serializationObject.directionRandomizer = this.directionRandomizer;
  59730. return serializationObject;
  59731. };
  59732. /**
  59733. * Parse properties from a JSON object
  59734. * @param serializationObject defines the JSON object
  59735. */
  59736. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59737. this.radius = serializationObject.radius;
  59738. this.height = serializationObject.height;
  59739. this.radiusRange = serializationObject.radiusRange;
  59740. this.directionRandomizer = serializationObject.directionRandomizer;
  59741. };
  59742. return CylinderParticleEmitter;
  59743. }());
  59744. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59745. /**
  59746. * Particle emitter emitting particles from the inside of a cylinder.
  59747. * It emits the particles randomly between two vectors.
  59748. */
  59749. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59750. __extends(CylinderDirectedParticleEmitter, _super);
  59751. /**
  59752. * Creates a new instance CylinderDirectedParticleEmitter
  59753. * @param radius the radius of the emission cylinder (1 by default)
  59754. * @param height the height of the emission cylinder (1 by default)
  59755. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59756. * @param direction1 the min limit of the emission direction (up vector by default)
  59757. * @param direction2 the max limit of the emission direction (up vector by default)
  59758. */
  59759. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59760. /**
  59761. * The min limit of the emission direction.
  59762. */
  59763. direction1,
  59764. /**
  59765. * The max limit of the emission direction.
  59766. */
  59767. direction2) {
  59768. if (radius === void 0) { radius = 1; }
  59769. if (height === void 0) { height = 1; }
  59770. if (radiusRange === void 0) { radiusRange = 1; }
  59771. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59772. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59773. var _this = _super.call(this, radius, height, radiusRange) || this;
  59774. _this.direction1 = direction1;
  59775. _this.direction2 = direction2;
  59776. return _this;
  59777. }
  59778. /**
  59779. * Called by the particle System when the direction is computed for the created particle.
  59780. * @param worldMatrix is the world matrix of the particle system
  59781. * @param directionToUpdate is the direction vector to update with the result
  59782. * @param particle is the particle we are computed the direction for
  59783. */
  59784. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59785. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59786. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59787. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59788. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59789. };
  59790. /**
  59791. * Clones the current emitter and returns a copy of it
  59792. * @returns the new emitter
  59793. */
  59794. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59795. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59796. BABYLON.Tools.DeepCopy(this, newOne);
  59797. return newOne;
  59798. };
  59799. /**
  59800. * Called by the GPUParticleSystem to setup the update shader
  59801. * @param effect defines the update shader
  59802. */
  59803. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59804. effect.setFloat("radius", this.radius);
  59805. effect.setFloat("height", this.height);
  59806. effect.setFloat("radiusRange", this.radiusRange);
  59807. effect.setVector3("direction1", this.direction1);
  59808. effect.setVector3("direction2", this.direction2);
  59809. };
  59810. /**
  59811. * Returns a string to use to update the GPU particles update shader
  59812. * @returns a string containng the defines string
  59813. */
  59814. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59815. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59816. };
  59817. /**
  59818. * Returns the string "CylinderDirectedParticleEmitter"
  59819. * @returns a string containing the class name
  59820. */
  59821. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59822. return "CylinderDirectedParticleEmitter";
  59823. };
  59824. /**
  59825. * Serializes the particle system to a JSON object.
  59826. * @returns the JSON object
  59827. */
  59828. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59829. var serializationObject = _super.prototype.serialize.call(this);
  59830. serializationObject.direction1 = this.direction1.asArray();
  59831. serializationObject.direction2 = this.direction2.asArray();
  59832. return serializationObject;
  59833. };
  59834. /**
  59835. * Parse properties from a JSON object
  59836. * @param serializationObject defines the JSON object
  59837. */
  59838. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59839. _super.prototype.parse.call(this, serializationObject);
  59840. this.direction1.copyFrom(serializationObject.direction1);
  59841. this.direction2.copyFrom(serializationObject.direction2);
  59842. };
  59843. return CylinderDirectedParticleEmitter;
  59844. }(CylinderParticleEmitter));
  59845. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59846. })(BABYLON || (BABYLON = {}));
  59847. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59848. var BABYLON;
  59849. (function (BABYLON) {
  59850. /**
  59851. * Particle emitter emitting particles from the inside of a cone.
  59852. * It emits the particles alongside the cone volume from the base to the particle.
  59853. * The emission direction might be randomized.
  59854. */
  59855. var ConeParticleEmitter = /** @class */ (function () {
  59856. /**
  59857. * Creates a new instance ConeParticleEmitter
  59858. * @param radius the radius of the emission cone (1 by default)
  59859. * @param angles the cone base angle (PI by default)
  59860. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59861. */
  59862. function ConeParticleEmitter(radius, angle,
  59863. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59864. directionRandomizer) {
  59865. if (radius === void 0) { radius = 1; }
  59866. if (angle === void 0) { angle = Math.PI; }
  59867. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59868. this.directionRandomizer = directionRandomizer;
  59869. /**
  59870. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59871. */
  59872. this.radiusRange = 1;
  59873. /**
  59874. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59875. */
  59876. this.heightRange = 1;
  59877. /**
  59878. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59879. */
  59880. this.emitFromSpawnPointOnly = false;
  59881. this.angle = angle;
  59882. this.radius = radius;
  59883. }
  59884. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59885. /**
  59886. * Gets or sets the radius of the emission cone
  59887. */
  59888. get: function () {
  59889. return this._radius;
  59890. },
  59891. set: function (value) {
  59892. this._radius = value;
  59893. this._buildHeight();
  59894. },
  59895. enumerable: true,
  59896. configurable: true
  59897. });
  59898. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59899. /**
  59900. * Gets or sets the angle of the emission cone
  59901. */
  59902. get: function () {
  59903. return this._angle;
  59904. },
  59905. set: function (value) {
  59906. this._angle = value;
  59907. this._buildHeight();
  59908. },
  59909. enumerable: true,
  59910. configurable: true
  59911. });
  59912. ConeParticleEmitter.prototype._buildHeight = function () {
  59913. if (this._angle !== 0) {
  59914. this._height = this._radius / Math.tan(this._angle / 2);
  59915. }
  59916. else {
  59917. this._height = 1;
  59918. }
  59919. };
  59920. /**
  59921. * Called by the particle System when the direction is computed for the created particle.
  59922. * @param worldMatrix is the world matrix of the particle system
  59923. * @param directionToUpdate is the direction vector to update with the result
  59924. * @param particle is the particle we are computed the direction for
  59925. */
  59926. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59927. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59928. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59929. }
  59930. else {
  59931. // measure the direction Vector from the emitter to the particle.
  59932. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59933. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59934. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59935. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59936. direction.x += randX;
  59937. direction.y += randY;
  59938. direction.z += randZ;
  59939. direction.normalize();
  59940. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59941. }
  59942. };
  59943. /**
  59944. * Called by the particle System when the position is computed for the created particle.
  59945. * @param worldMatrix is the world matrix of the particle system
  59946. * @param positionToUpdate is the position vector to update with the result
  59947. * @param particle is the particle we are computed the position for
  59948. */
  59949. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59950. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59951. var h;
  59952. if (!this.emitFromSpawnPointOnly) {
  59953. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59954. // Better distribution in a cone at normal angles.
  59955. h = 1 - h * h;
  59956. }
  59957. else {
  59958. h = 0.0001;
  59959. }
  59960. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59961. radius = radius * h;
  59962. var randX = radius * Math.sin(s);
  59963. var randZ = radius * Math.cos(s);
  59964. var randY = h * this._height;
  59965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59966. };
  59967. /**
  59968. * Clones the current emitter and returns a copy of it
  59969. * @returns the new emitter
  59970. */
  59971. ConeParticleEmitter.prototype.clone = function () {
  59972. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59973. BABYLON.Tools.DeepCopy(this, newOne);
  59974. return newOne;
  59975. };
  59976. /**
  59977. * Called by the GPUParticleSystem to setup the update shader
  59978. * @param effect defines the update shader
  59979. */
  59980. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  59981. effect.setFloat2("radius", this._radius, this.radiusRange);
  59982. effect.setFloat("coneAngle", this._angle);
  59983. effect.setFloat2("height", this._height, this.heightRange);
  59984. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59985. };
  59986. /**
  59987. * Returns a string to use to update the GPU particles update shader
  59988. * @returns a string containng the defines string
  59989. */
  59990. ConeParticleEmitter.prototype.getEffectDefines = function () {
  59991. var defines = "#define CONEEMITTER";
  59992. if (this.emitFromSpawnPointOnly) {
  59993. defines += "\n#define CONEEMITTERSPAWNPOINT";
  59994. }
  59995. return defines;
  59996. };
  59997. /**
  59998. * Returns the string "ConeParticleEmitter"
  59999. * @returns a string containing the class name
  60000. */
  60001. ConeParticleEmitter.prototype.getClassName = function () {
  60002. return "ConeParticleEmitter";
  60003. };
  60004. /**
  60005. * Serializes the particle system to a JSON object.
  60006. * @returns the JSON object
  60007. */
  60008. ConeParticleEmitter.prototype.serialize = function () {
  60009. var serializationObject = {};
  60010. serializationObject.type = this.getClassName();
  60011. serializationObject.radius = this._radius;
  60012. serializationObject.angle = this._angle;
  60013. serializationObject.directionRandomizer = this.directionRandomizer;
  60014. return serializationObject;
  60015. };
  60016. /**
  60017. * Parse properties from a JSON object
  60018. * @param serializationObject defines the JSON object
  60019. */
  60020. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60021. this.radius = serializationObject.radius;
  60022. this.angle = serializationObject.angle;
  60023. this.directionRandomizer = serializationObject.directionRandomizer;
  60024. };
  60025. return ConeParticleEmitter;
  60026. }());
  60027. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60028. })(BABYLON || (BABYLON = {}));
  60029. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60030. var BABYLON;
  60031. (function (BABYLON) {
  60032. /**
  60033. * Particle emitter emitting particles from the inside of a sphere.
  60034. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60035. */
  60036. var SphereParticleEmitter = /** @class */ (function () {
  60037. /**
  60038. * Creates a new instance SphereParticleEmitter
  60039. * @param radius the radius of the emission sphere (1 by default)
  60040. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60041. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60042. */
  60043. function SphereParticleEmitter(
  60044. /**
  60045. * The radius of the emission sphere.
  60046. */
  60047. radius,
  60048. /**
  60049. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60050. */
  60051. radiusRange,
  60052. /**
  60053. * How much to randomize the particle direction [0-1].
  60054. */
  60055. directionRandomizer) {
  60056. if (radius === void 0) { radius = 1; }
  60057. if (radiusRange === void 0) { radiusRange = 1; }
  60058. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60059. this.radius = radius;
  60060. this.radiusRange = radiusRange;
  60061. this.directionRandomizer = directionRandomizer;
  60062. }
  60063. /**
  60064. * Called by the particle System when the direction is computed for the created particle.
  60065. * @param worldMatrix is the world matrix of the particle system
  60066. * @param directionToUpdate is the direction vector to update with the result
  60067. * @param particle is the particle we are computed the direction for
  60068. */
  60069. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60070. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60071. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60072. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60073. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60074. direction.x += randX;
  60075. direction.y += randY;
  60076. direction.z += randZ;
  60077. direction.normalize();
  60078. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60079. };
  60080. /**
  60081. * Called by the particle System when the position is computed for the created particle.
  60082. * @param worldMatrix is the world matrix of the particle system
  60083. * @param positionToUpdate is the position vector to update with the result
  60084. * @param particle is the particle we are computed the position for
  60085. */
  60086. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60087. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60088. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60089. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60090. var theta = Math.acos(2 * v - 1);
  60091. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60092. var randY = randRadius * Math.cos(theta);
  60093. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60095. };
  60096. /**
  60097. * Clones the current emitter and returns a copy of it
  60098. * @returns the new emitter
  60099. */
  60100. SphereParticleEmitter.prototype.clone = function () {
  60101. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60102. BABYLON.Tools.DeepCopy(this, newOne);
  60103. return newOne;
  60104. };
  60105. /**
  60106. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60107. * @param effect defines the update shader
  60108. */
  60109. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60110. effect.setFloat("radius", this.radius);
  60111. effect.setFloat("radiusRange", this.radiusRange);
  60112. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60113. };
  60114. /**
  60115. * Returns a string to use to update the GPU particles update shader
  60116. * @returns a string containng the defines string
  60117. */
  60118. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60119. return "#define SPHEREEMITTER";
  60120. };
  60121. /**
  60122. * Returns the string "SphereParticleEmitter"
  60123. * @returns a string containing the class name
  60124. */
  60125. SphereParticleEmitter.prototype.getClassName = function () {
  60126. return "SphereParticleEmitter";
  60127. };
  60128. /**
  60129. * Serializes the particle system to a JSON object.
  60130. * @returns the JSON object
  60131. */
  60132. SphereParticleEmitter.prototype.serialize = function () {
  60133. var serializationObject = {};
  60134. serializationObject.type = this.getClassName();
  60135. serializationObject.radius = this.radius;
  60136. serializationObject.radiusRange = this.radiusRange;
  60137. serializationObject.directionRandomizer = this.directionRandomizer;
  60138. return serializationObject;
  60139. };
  60140. /**
  60141. * Parse properties from a JSON object
  60142. * @param serializationObject defines the JSON object
  60143. */
  60144. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60145. this.radius = serializationObject.radius;
  60146. this.radiusRange = serializationObject.radiusRange;
  60147. this.directionRandomizer = serializationObject.directionRandomizer;
  60148. };
  60149. return SphereParticleEmitter;
  60150. }());
  60151. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60152. /**
  60153. * Particle emitter emitting particles from the inside of a sphere.
  60154. * It emits the particles randomly between two vectors.
  60155. */
  60156. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60157. __extends(SphereDirectedParticleEmitter, _super);
  60158. /**
  60159. * Creates a new instance SphereDirectedParticleEmitter
  60160. * @param radius the radius of the emission sphere (1 by default)
  60161. * @param direction1 the min limit of the emission direction (up vector by default)
  60162. * @param direction2 the max limit of the emission direction (up vector by default)
  60163. */
  60164. function SphereDirectedParticleEmitter(radius,
  60165. /**
  60166. * The min limit of the emission direction.
  60167. */
  60168. direction1,
  60169. /**
  60170. * The max limit of the emission direction.
  60171. */
  60172. direction2) {
  60173. if (radius === void 0) { radius = 1; }
  60174. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60175. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60176. var _this = _super.call(this, radius) || this;
  60177. _this.direction1 = direction1;
  60178. _this.direction2 = direction2;
  60179. return _this;
  60180. }
  60181. /**
  60182. * Called by the particle System when the direction is computed for the created particle.
  60183. * @param worldMatrix is the world matrix of the particle system
  60184. * @param directionToUpdate is the direction vector to update with the result
  60185. * @param particle is the particle we are computed the direction for
  60186. */
  60187. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60188. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60189. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60190. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60191. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60192. };
  60193. /**
  60194. * Clones the current emitter and returns a copy of it
  60195. * @returns the new emitter
  60196. */
  60197. SphereDirectedParticleEmitter.prototype.clone = function () {
  60198. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60199. BABYLON.Tools.DeepCopy(this, newOne);
  60200. return newOne;
  60201. };
  60202. /**
  60203. * Called by the GPUParticleSystem to setup the update shader
  60204. * @param effect defines the update shader
  60205. */
  60206. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60207. effect.setFloat("radius", this.radius);
  60208. effect.setFloat("radiusRange", this.radiusRange);
  60209. effect.setVector3("direction1", this.direction1);
  60210. effect.setVector3("direction2", this.direction2);
  60211. };
  60212. /**
  60213. * Returns a string to use to update the GPU particles update shader
  60214. * @returns a string containng the defines string
  60215. */
  60216. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60217. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60218. };
  60219. /**
  60220. * Returns the string "SphereDirectedParticleEmitter"
  60221. * @returns a string containing the class name
  60222. */
  60223. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60224. return "SphereDirectedParticleEmitter";
  60225. };
  60226. /**
  60227. * Serializes the particle system to a JSON object.
  60228. * @returns the JSON object
  60229. */
  60230. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60231. var serializationObject = _super.prototype.serialize.call(this);
  60232. serializationObject.direction1 = this.direction1.asArray();
  60233. serializationObject.direction2 = this.direction2.asArray();
  60234. return serializationObject;
  60235. };
  60236. /**
  60237. * Parse properties from a JSON object
  60238. * @param serializationObject defines the JSON object
  60239. */
  60240. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60241. _super.prototype.parse.call(this, serializationObject);
  60242. this.direction1.copyFrom(serializationObject.direction1);
  60243. this.direction2.copyFrom(serializationObject.direction2);
  60244. };
  60245. return SphereDirectedParticleEmitter;
  60246. }(SphereParticleEmitter));
  60247. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60248. })(BABYLON || (BABYLON = {}));
  60249. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60250. var BABYLON;
  60251. (function (BABYLON) {
  60252. /**
  60253. * Particle emitter emitting particles from the inside of a hemisphere.
  60254. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60255. */
  60256. var HemisphericParticleEmitter = /** @class */ (function () {
  60257. /**
  60258. * Creates a new instance HemisphericParticleEmitter
  60259. * @param radius the radius of the emission hemisphere (1 by default)
  60260. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60261. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60262. */
  60263. function HemisphericParticleEmitter(
  60264. /**
  60265. * The radius of the emission hemisphere.
  60266. */
  60267. radius,
  60268. /**
  60269. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60270. */
  60271. radiusRange,
  60272. /**
  60273. * How much to randomize the particle direction [0-1].
  60274. */
  60275. directionRandomizer) {
  60276. if (radius === void 0) { radius = 1; }
  60277. if (radiusRange === void 0) { radiusRange = 1; }
  60278. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60279. this.radius = radius;
  60280. this.radiusRange = radiusRange;
  60281. this.directionRandomizer = directionRandomizer;
  60282. }
  60283. /**
  60284. * Called by the particle System when the direction is computed for the created particle.
  60285. * @param worldMatrix is the world matrix of the particle system
  60286. * @param directionToUpdate is the direction vector to update with the result
  60287. * @param particle is the particle we are computed the direction for
  60288. */
  60289. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60290. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60291. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60292. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60293. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60294. direction.x += randX;
  60295. direction.y += randY;
  60296. direction.z += randZ;
  60297. direction.normalize();
  60298. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60299. };
  60300. /**
  60301. * Called by the particle System when the position is computed for the created particle.
  60302. * @param worldMatrix is the world matrix of the particle system
  60303. * @param positionToUpdate is the position vector to update with the result
  60304. * @param particle is the particle we are computed the position for
  60305. */
  60306. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60307. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60308. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60309. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60310. var theta = Math.acos(2 * v - 1);
  60311. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60312. var randY = randRadius * Math.cos(theta);
  60313. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60315. };
  60316. /**
  60317. * Clones the current emitter and returns a copy of it
  60318. * @returns the new emitter
  60319. */
  60320. HemisphericParticleEmitter.prototype.clone = function () {
  60321. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60322. BABYLON.Tools.DeepCopy(this, newOne);
  60323. return newOne;
  60324. };
  60325. /**
  60326. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60327. * @param effect defines the update shader
  60328. */
  60329. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60330. effect.setFloat("radius", this.radius);
  60331. effect.setFloat("radiusRange", this.radiusRange);
  60332. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60333. };
  60334. /**
  60335. * Returns a string to use to update the GPU particles update shader
  60336. * @returns a string containng the defines string
  60337. */
  60338. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60339. return "#define HEMISPHERICEMITTER";
  60340. };
  60341. /**
  60342. * Returns the string "HemisphericParticleEmitter"
  60343. * @returns a string containing the class name
  60344. */
  60345. HemisphericParticleEmitter.prototype.getClassName = function () {
  60346. return "HemisphericParticleEmitter";
  60347. };
  60348. /**
  60349. * Serializes the particle system to a JSON object.
  60350. * @returns the JSON object
  60351. */
  60352. HemisphericParticleEmitter.prototype.serialize = function () {
  60353. var serializationObject = {};
  60354. serializationObject.type = this.getClassName();
  60355. serializationObject.radius = this.radius;
  60356. serializationObject.radiusRange = this.radiusRange;
  60357. serializationObject.directionRandomizer = this.directionRandomizer;
  60358. return serializationObject;
  60359. };
  60360. /**
  60361. * Parse properties from a JSON object
  60362. * @param serializationObject defines the JSON object
  60363. */
  60364. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60365. this.radius = serializationObject.radius;
  60366. this.radiusRange = serializationObject.radiusRange;
  60367. this.directionRandomizer = serializationObject.directionRandomizer;
  60368. };
  60369. return HemisphericParticleEmitter;
  60370. }());
  60371. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60372. })(BABYLON || (BABYLON = {}));
  60373. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60374. var BABYLON;
  60375. (function (BABYLON) {
  60376. /**
  60377. * Particle emitter emitting particles from a point.
  60378. * It emits the particles randomly between 2 given directions.
  60379. */
  60380. var PointParticleEmitter = /** @class */ (function () {
  60381. /**
  60382. * Creates a new instance PointParticleEmitter
  60383. */
  60384. function PointParticleEmitter() {
  60385. /**
  60386. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60387. */
  60388. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60389. /**
  60390. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60391. */
  60392. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60393. }
  60394. /**
  60395. * Called by the particle System when the direction is computed for the created particle.
  60396. * @param worldMatrix is the world matrix of the particle system
  60397. * @param directionToUpdate is the direction vector to update with the result
  60398. * @param particle is the particle we are computed the direction for
  60399. */
  60400. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60401. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60402. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60403. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60404. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60405. };
  60406. /**
  60407. * Called by the particle System when the position is computed for the created particle.
  60408. * @param worldMatrix is the world matrix of the particle system
  60409. * @param positionToUpdate is the position vector to update with the result
  60410. * @param particle is the particle we are computed the position for
  60411. */
  60412. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60413. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60414. };
  60415. /**
  60416. * Clones the current emitter and returns a copy of it
  60417. * @returns the new emitter
  60418. */
  60419. PointParticleEmitter.prototype.clone = function () {
  60420. var newOne = new PointParticleEmitter();
  60421. BABYLON.Tools.DeepCopy(this, newOne);
  60422. return newOne;
  60423. };
  60424. /**
  60425. * Called by the GPUParticleSystem to setup the update shader
  60426. * @param effect defines the update shader
  60427. */
  60428. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60429. effect.setVector3("direction1", this.direction1);
  60430. effect.setVector3("direction2", this.direction2);
  60431. };
  60432. /**
  60433. * Returns a string to use to update the GPU particles update shader
  60434. * @returns a string containng the defines string
  60435. */
  60436. PointParticleEmitter.prototype.getEffectDefines = function () {
  60437. return "#define POINTEMITTER";
  60438. };
  60439. /**
  60440. * Returns the string "PointParticleEmitter"
  60441. * @returns a string containing the class name
  60442. */
  60443. PointParticleEmitter.prototype.getClassName = function () {
  60444. return "PointParticleEmitter";
  60445. };
  60446. /**
  60447. * Serializes the particle system to a JSON object.
  60448. * @returns the JSON object
  60449. */
  60450. PointParticleEmitter.prototype.serialize = function () {
  60451. var serializationObject = {};
  60452. serializationObject.type = this.getClassName();
  60453. serializationObject.direction1 = this.direction1.asArray();
  60454. serializationObject.direction2 = this.direction2.asArray();
  60455. return serializationObject;
  60456. };
  60457. /**
  60458. * Parse properties from a JSON object
  60459. * @param serializationObject defines the JSON object
  60460. */
  60461. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60462. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60463. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60464. };
  60465. return PointParticleEmitter;
  60466. }());
  60467. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60468. })(BABYLON || (BABYLON = {}));
  60469. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60470. var BABYLON;
  60471. (function (BABYLON) {
  60472. // Adds the parsers to the scene parsers.
  60473. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60474. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60475. if (!individualParser) {
  60476. return;
  60477. }
  60478. // Particles Systems
  60479. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60480. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60481. var parsedParticleSystem = parsedData.particleSystems[index];
  60482. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60483. }
  60484. }
  60485. });
  60486. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60487. if (parsedParticleSystem.activeParticleCount) {
  60488. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60489. return ps;
  60490. }
  60491. else {
  60492. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60493. return ps;
  60494. }
  60495. });
  60496. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60497. if (uniformsNames === void 0) { uniformsNames = []; }
  60498. if (samplers === void 0) { samplers = []; }
  60499. if (defines === void 0) { defines = ""; }
  60500. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60501. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60502. if (defines.indexOf(" BILLBOARD") === -1) {
  60503. defines += "\n#define BILLBOARD\n";
  60504. }
  60505. if (samplers.indexOf("diffuseSampler") === -1) {
  60506. samplers.push("diffuseSampler");
  60507. }
  60508. return this.createEffect({
  60509. vertex: "particles",
  60510. fragmentElement: fragmentName
  60511. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60512. };
  60513. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60514. var results = new Array();
  60515. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60516. var particleSystem = this.getScene().particleSystems[index];
  60517. if (particleSystem.emitter === this) {
  60518. results.push(particleSystem);
  60519. }
  60520. }
  60521. return results;
  60522. };
  60523. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60524. var results = new Array();
  60525. var descendants = this.getDescendants();
  60526. descendants.push(this);
  60527. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60528. var particleSystem = this.getScene().particleSystems[index];
  60529. var emitter = particleSystem.emitter;
  60530. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60531. results.push(particleSystem);
  60532. }
  60533. }
  60534. return results;
  60535. };
  60536. })(BABYLON || (BABYLON = {}));
  60537. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60538. var BABYLON;
  60539. (function (BABYLON) {
  60540. /**
  60541. * Type of sub emitter
  60542. */
  60543. var SubEmitterType;
  60544. (function (SubEmitterType) {
  60545. /**
  60546. * Attached to the particle over it's lifetime
  60547. */
  60548. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60549. /**
  60550. * Created when the particle dies
  60551. */
  60552. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60553. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60554. /**
  60555. * Sub emitter class used to emit particles from an existing particle
  60556. */
  60557. var SubEmitter = /** @class */ (function () {
  60558. /**
  60559. * Creates a sub emitter
  60560. * @param particleSystem the particle system to be used by the sub emitter
  60561. */
  60562. function SubEmitter(
  60563. /**
  60564. * the particle system to be used by the sub emitter
  60565. */
  60566. particleSystem) {
  60567. this.particleSystem = particleSystem;
  60568. /**
  60569. * Type of the submitter (Default: END)
  60570. */
  60571. this.type = SubEmitterType.END;
  60572. /**
  60573. * 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)
  60574. * Note: This only is supported when using an emitter of type Mesh
  60575. */
  60576. this.inheritDirection = false;
  60577. /**
  60578. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60579. */
  60580. this.inheritedVelocityAmount = 0;
  60581. }
  60582. /**
  60583. * Clones the sub emitter
  60584. * @returns the cloned sub emitter
  60585. */
  60586. SubEmitter.prototype.clone = function () {
  60587. // Clone particle system
  60588. var emitter = this.particleSystem.emitter;
  60589. if (!emitter) {
  60590. emitter = new BABYLON.Vector3();
  60591. }
  60592. else if (emitter instanceof BABYLON.Vector3) {
  60593. emitter = emitter.clone();
  60594. }
  60595. else if (emitter instanceof BABYLON.AbstractMesh) {
  60596. emitter = new BABYLON.Mesh("", emitter.getScene());
  60597. emitter.isVisible = false;
  60598. }
  60599. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60600. // Clone properties
  60601. clone.type = this.type;
  60602. clone.inheritDirection = this.inheritDirection;
  60603. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60604. clone.particleSystem._disposeEmitterOnDispose = true;
  60605. clone.particleSystem.disposeOnStop = true;
  60606. return clone;
  60607. };
  60608. /**
  60609. * Serialize current object to a JSON object
  60610. * @returns the serialized object
  60611. */
  60612. SubEmitter.prototype.serialize = function () {
  60613. var serializationObject = {};
  60614. serializationObject.type = this.type;
  60615. serializationObject.inheritDirection = this.inheritDirection;
  60616. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60617. serializationObject.particleSystem = this.particleSystem.serialize();
  60618. return serializationObject;
  60619. };
  60620. /**
  60621. * Creates a new SubEmitter from a serialized JSON version
  60622. * @param serializationObject defines the JSON object to read from
  60623. * @param scene defines the hosting scene
  60624. * @param rootUrl defines the rootUrl for data loading
  60625. * @returns a new SubEmitter
  60626. */
  60627. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60628. var system = serializationObject.particleSystem;
  60629. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60630. subEmitter.type = serializationObject.type;
  60631. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60632. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60633. subEmitter.particleSystem._isSubEmitter = true;
  60634. return subEmitter;
  60635. };
  60636. /** Release associated resources */
  60637. SubEmitter.prototype.dispose = function () {
  60638. this.particleSystem.dispose();
  60639. };
  60640. return SubEmitter;
  60641. }());
  60642. BABYLON.SubEmitter = SubEmitter;
  60643. })(BABYLON || (BABYLON = {}));
  60644. //# sourceMappingURL=babylon.subEmitter.js.map
  60645. var BABYLON;
  60646. (function (BABYLON) {
  60647. var ShaderMaterial = /** @class */ (function (_super) {
  60648. __extends(ShaderMaterial, _super);
  60649. function ShaderMaterial(name, scene, shaderPath, options) {
  60650. var _this = _super.call(this, name, scene) || this;
  60651. _this._textures = {};
  60652. _this._textureArrays = {};
  60653. _this._floats = {};
  60654. _this._ints = {};
  60655. _this._floatsArrays = {};
  60656. _this._colors3 = {};
  60657. _this._colors3Arrays = {};
  60658. _this._colors4 = {};
  60659. _this._vectors2 = {};
  60660. _this._vectors3 = {};
  60661. _this._vectors4 = {};
  60662. _this._matrices = {};
  60663. _this._matrices3x3 = {};
  60664. _this._matrices2x2 = {};
  60665. _this._vectors2Arrays = {};
  60666. _this._vectors3Arrays = {};
  60667. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60668. _this._shaderPath = shaderPath;
  60669. options.needAlphaBlending = options.needAlphaBlending || false;
  60670. options.needAlphaTesting = options.needAlphaTesting || false;
  60671. options.attributes = options.attributes || ["position", "normal", "uv"];
  60672. options.uniforms = options.uniforms || ["worldViewProjection"];
  60673. options.uniformBuffers = options.uniformBuffers || [];
  60674. options.samplers = options.samplers || [];
  60675. options.defines = options.defines || [];
  60676. _this._options = options;
  60677. return _this;
  60678. }
  60679. ShaderMaterial.prototype.getClassName = function () {
  60680. return "ShaderMaterial";
  60681. };
  60682. ShaderMaterial.prototype.needAlphaBlending = function () {
  60683. return this._options.needAlphaBlending;
  60684. };
  60685. ShaderMaterial.prototype.needAlphaTesting = function () {
  60686. return this._options.needAlphaTesting;
  60687. };
  60688. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60689. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60690. this._options.uniforms.push(uniformName);
  60691. }
  60692. };
  60693. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60694. if (this._options.samplers.indexOf(name) === -1) {
  60695. this._options.samplers.push(name);
  60696. }
  60697. this._textures[name] = texture;
  60698. return this;
  60699. };
  60700. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60701. if (this._options.samplers.indexOf(name) === -1) {
  60702. this._options.samplers.push(name);
  60703. }
  60704. this._checkUniform(name);
  60705. this._textureArrays[name] = textures;
  60706. return this;
  60707. };
  60708. ShaderMaterial.prototype.setFloat = function (name, value) {
  60709. this._checkUniform(name);
  60710. this._floats[name] = value;
  60711. return this;
  60712. };
  60713. ShaderMaterial.prototype.setInt = function (name, value) {
  60714. this._checkUniform(name);
  60715. this._ints[name] = value;
  60716. return this;
  60717. };
  60718. ShaderMaterial.prototype.setFloats = function (name, value) {
  60719. this._checkUniform(name);
  60720. this._floatsArrays[name] = value;
  60721. return this;
  60722. };
  60723. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60724. this._checkUniform(name);
  60725. this._colors3[name] = value;
  60726. return this;
  60727. };
  60728. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60729. this._checkUniform(name);
  60730. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60731. color.toArray(arr, arr.length);
  60732. return arr;
  60733. }, []);
  60734. return this;
  60735. };
  60736. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60737. this._checkUniform(name);
  60738. this._colors4[name] = value;
  60739. return this;
  60740. };
  60741. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60742. this._checkUniform(name);
  60743. this._vectors2[name] = value;
  60744. return this;
  60745. };
  60746. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60747. this._checkUniform(name);
  60748. this._vectors3[name] = value;
  60749. return this;
  60750. };
  60751. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60752. this._checkUniform(name);
  60753. this._vectors4[name] = value;
  60754. return this;
  60755. };
  60756. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60757. this._checkUniform(name);
  60758. this._matrices[name] = value;
  60759. return this;
  60760. };
  60761. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60762. this._checkUniform(name);
  60763. this._matrices3x3[name] = value;
  60764. return this;
  60765. };
  60766. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60767. this._checkUniform(name);
  60768. this._matrices2x2[name] = value;
  60769. return this;
  60770. };
  60771. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60772. this._checkUniform(name);
  60773. this._vectors2Arrays[name] = value;
  60774. return this;
  60775. };
  60776. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60777. this._checkUniform(name);
  60778. this._vectors3Arrays[name] = value;
  60779. return this;
  60780. };
  60781. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60782. if (!mesh) {
  60783. return true;
  60784. }
  60785. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60786. return false;
  60787. }
  60788. return false;
  60789. };
  60790. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60791. var scene = this.getScene();
  60792. var engine = scene.getEngine();
  60793. if (!this.checkReadyOnEveryCall) {
  60794. if (this._renderId === scene.getRenderId()) {
  60795. if (this._checkCache(scene, mesh, useInstances)) {
  60796. return true;
  60797. }
  60798. }
  60799. }
  60800. // Instances
  60801. var defines = [];
  60802. var attribs = [];
  60803. var fallbacks = new BABYLON.EffectFallbacks();
  60804. if (useInstances) {
  60805. defines.push("#define INSTANCES");
  60806. }
  60807. for (var index = 0; index < this._options.defines.length; index++) {
  60808. defines.push(this._options.defines[index]);
  60809. }
  60810. for (var index = 0; index < this._options.attributes.length; index++) {
  60811. attribs.push(this._options.attributes[index]);
  60812. }
  60813. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60814. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60815. defines.push("#define VERTEXCOLOR");
  60816. }
  60817. // Bones
  60818. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60819. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60820. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60821. if (mesh.numBoneInfluencers > 4) {
  60822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60824. }
  60825. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60826. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60827. fallbacks.addCPUSkinningFallback(0, mesh);
  60828. if (this._options.uniforms.indexOf("mBones") === -1) {
  60829. this._options.uniforms.push("mBones");
  60830. }
  60831. }
  60832. else {
  60833. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60834. }
  60835. // Textures
  60836. for (var name in this._textures) {
  60837. if (!this._textures[name].isReady()) {
  60838. return false;
  60839. }
  60840. }
  60841. // Alpha test
  60842. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60843. defines.push("#define ALPHATEST");
  60844. }
  60845. var previousEffect = this._effect;
  60846. var join = defines.join("\n");
  60847. this._effect = engine.createEffect(this._shaderPath, {
  60848. attributes: attribs,
  60849. uniformsNames: this._options.uniforms,
  60850. uniformBuffersNames: this._options.uniformBuffers,
  60851. samplers: this._options.samplers,
  60852. defines: join,
  60853. fallbacks: fallbacks,
  60854. onCompiled: this.onCompiled,
  60855. onError: this.onError
  60856. }, engine);
  60857. if (!this._effect.isReady()) {
  60858. return false;
  60859. }
  60860. if (previousEffect !== this._effect) {
  60861. scene.resetCachedMaterial();
  60862. }
  60863. this._renderId = scene.getRenderId();
  60864. return true;
  60865. };
  60866. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60867. var scene = this.getScene();
  60868. if (!this._effect) {
  60869. return;
  60870. }
  60871. if (this._options.uniforms.indexOf("world") !== -1) {
  60872. this._effect.setMatrix("world", world);
  60873. }
  60874. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60875. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60876. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60877. }
  60878. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60879. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60880. }
  60881. };
  60882. ShaderMaterial.prototype.bind = function (world, mesh) {
  60883. // Std values
  60884. this.bindOnlyWorldMatrix(world);
  60885. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60886. if (this._options.uniforms.indexOf("view") !== -1) {
  60887. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60888. }
  60889. if (this._options.uniforms.indexOf("projection") !== -1) {
  60890. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60891. }
  60892. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60893. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60894. }
  60895. // Bones
  60896. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60897. var name;
  60898. // Texture
  60899. for (name in this._textures) {
  60900. this._effect.setTexture(name, this._textures[name]);
  60901. }
  60902. // Texture arrays
  60903. for (name in this._textureArrays) {
  60904. this._effect.setTextureArray(name, this._textureArrays[name]);
  60905. }
  60906. // Int
  60907. for (name in this._ints) {
  60908. this._effect.setInt(name, this._ints[name]);
  60909. }
  60910. // Float
  60911. for (name in this._floats) {
  60912. this._effect.setFloat(name, this._floats[name]);
  60913. }
  60914. // Floats
  60915. for (name in this._floatsArrays) {
  60916. this._effect.setArray(name, this._floatsArrays[name]);
  60917. }
  60918. // Color3
  60919. for (name in this._colors3) {
  60920. this._effect.setColor3(name, this._colors3[name]);
  60921. }
  60922. for (name in this._colors3Arrays) {
  60923. this._effect.setArray3(name, this._colors3Arrays[name]);
  60924. }
  60925. // Color4
  60926. for (name in this._colors4) {
  60927. var color = this._colors4[name];
  60928. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60929. }
  60930. // Vector2
  60931. for (name in this._vectors2) {
  60932. this._effect.setVector2(name, this._vectors2[name]);
  60933. }
  60934. // Vector3
  60935. for (name in this._vectors3) {
  60936. this._effect.setVector3(name, this._vectors3[name]);
  60937. }
  60938. // Vector4
  60939. for (name in this._vectors4) {
  60940. this._effect.setVector4(name, this._vectors4[name]);
  60941. }
  60942. // Matrix
  60943. for (name in this._matrices) {
  60944. this._effect.setMatrix(name, this._matrices[name]);
  60945. }
  60946. // Matrix 3x3
  60947. for (name in this._matrices3x3) {
  60948. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60949. }
  60950. // Matrix 2x2
  60951. for (name in this._matrices2x2) {
  60952. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60953. }
  60954. // Vector2Array
  60955. for (name in this._vectors2Arrays) {
  60956. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60957. }
  60958. // Vector3Array
  60959. for (name in this._vectors3Arrays) {
  60960. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60961. }
  60962. }
  60963. this._afterBind(mesh);
  60964. };
  60965. ShaderMaterial.prototype.getActiveTextures = function () {
  60966. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60967. for (var name in this._textures) {
  60968. activeTextures.push(this._textures[name]);
  60969. }
  60970. for (var name in this._textureArrays) {
  60971. var array = this._textureArrays[name];
  60972. for (var index = 0; index < array.length; index++) {
  60973. activeTextures.push(array[index]);
  60974. }
  60975. }
  60976. return activeTextures;
  60977. };
  60978. ShaderMaterial.prototype.hasTexture = function (texture) {
  60979. if (_super.prototype.hasTexture.call(this, texture)) {
  60980. return true;
  60981. }
  60982. for (var name in this._textures) {
  60983. if (this._textures[name] === texture) {
  60984. return true;
  60985. }
  60986. }
  60987. for (var name in this._textureArrays) {
  60988. var array = this._textureArrays[name];
  60989. for (var index = 0; index < array.length; index++) {
  60990. if (array[index] === texture) {
  60991. return true;
  60992. }
  60993. }
  60994. }
  60995. return false;
  60996. };
  60997. ShaderMaterial.prototype.clone = function (name) {
  60998. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60999. return newShaderMaterial;
  61000. };
  61001. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61002. if (forceDisposeTextures) {
  61003. var name;
  61004. for (name in this._textures) {
  61005. this._textures[name].dispose();
  61006. }
  61007. for (name in this._textureArrays) {
  61008. var array = this._textureArrays[name];
  61009. for (var index = 0; index < array.length; index++) {
  61010. array[index].dispose();
  61011. }
  61012. }
  61013. }
  61014. this._textures = {};
  61015. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61016. };
  61017. ShaderMaterial.prototype.serialize = function () {
  61018. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61019. serializationObject.customType = "BABYLON.ShaderMaterial";
  61020. serializationObject.options = this._options;
  61021. serializationObject.shaderPath = this._shaderPath;
  61022. var name;
  61023. // Texture
  61024. serializationObject.textures = {};
  61025. for (name in this._textures) {
  61026. serializationObject.textures[name] = this._textures[name].serialize();
  61027. }
  61028. // Texture arrays
  61029. serializationObject.textureArrays = {};
  61030. for (name in this._textureArrays) {
  61031. serializationObject.textureArrays[name] = [];
  61032. var array = this._textureArrays[name];
  61033. for (var index = 0; index < array.length; index++) {
  61034. serializationObject.textureArrays[name].push(array[index].serialize());
  61035. }
  61036. }
  61037. // Float
  61038. serializationObject.floats = {};
  61039. for (name in this._floats) {
  61040. serializationObject.floats[name] = this._floats[name];
  61041. }
  61042. // Float s
  61043. serializationObject.FloatArrays = {};
  61044. for (name in this._floatsArrays) {
  61045. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61046. }
  61047. // Color3
  61048. serializationObject.colors3 = {};
  61049. for (name in this._colors3) {
  61050. serializationObject.colors3[name] = this._colors3[name].asArray();
  61051. }
  61052. // Color3 array
  61053. serializationObject.colors3Arrays = {};
  61054. for (name in this._colors3Arrays) {
  61055. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61056. }
  61057. // Color4
  61058. serializationObject.colors4 = {};
  61059. for (name in this._colors4) {
  61060. serializationObject.colors4[name] = this._colors4[name].asArray();
  61061. }
  61062. // Vector2
  61063. serializationObject.vectors2 = {};
  61064. for (name in this._vectors2) {
  61065. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61066. }
  61067. // Vector3
  61068. serializationObject.vectors3 = {};
  61069. for (name in this._vectors3) {
  61070. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61071. }
  61072. // Vector4
  61073. serializationObject.vectors4 = {};
  61074. for (name in this._vectors4) {
  61075. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61076. }
  61077. // Matrix
  61078. serializationObject.matrices = {};
  61079. for (name in this._matrices) {
  61080. serializationObject.matrices[name] = this._matrices[name].asArray();
  61081. }
  61082. // Matrix 3x3
  61083. serializationObject.matrices3x3 = {};
  61084. for (name in this._matrices3x3) {
  61085. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61086. }
  61087. // Matrix 2x2
  61088. serializationObject.matrices2x2 = {};
  61089. for (name in this._matrices2x2) {
  61090. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  61091. }
  61092. // Vector2Array
  61093. serializationObject.vectors2Arrays = {};
  61094. for (name in this._vectors2Arrays) {
  61095. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  61096. }
  61097. // Vector3Array
  61098. serializationObject.vectors3Arrays = {};
  61099. for (name in this._vectors3Arrays) {
  61100. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  61101. }
  61102. return serializationObject;
  61103. };
  61104. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  61105. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  61106. var name;
  61107. // Texture
  61108. for (name in source.textures) {
  61109. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  61110. }
  61111. // Texture arrays
  61112. for (name in source.textureArrays) {
  61113. var array = source.textureArrays[name];
  61114. var textureArray = new Array();
  61115. for (var index = 0; index < array.length; index++) {
  61116. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  61117. }
  61118. material.setTextureArray(name, textureArray);
  61119. }
  61120. // Float
  61121. for (name in source.floats) {
  61122. material.setFloat(name, source.floats[name]);
  61123. }
  61124. // Float s
  61125. for (name in source.floatsArrays) {
  61126. material.setFloats(name, source.floatsArrays[name]);
  61127. }
  61128. // Color3
  61129. for (name in source.colors3) {
  61130. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  61131. }
  61132. // Color3 arrays
  61133. for (name in source.colors3Arrays) {
  61134. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  61135. if (i % 3 === 0) {
  61136. arr.push([num]);
  61137. }
  61138. else {
  61139. arr[arr.length - 1].push(num);
  61140. }
  61141. return arr;
  61142. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  61143. material.setColor3Array(name, colors);
  61144. }
  61145. // Color4
  61146. for (name in source.colors4) {
  61147. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  61148. }
  61149. // Vector2
  61150. for (name in source.vectors2) {
  61151. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  61152. }
  61153. // Vector3
  61154. for (name in source.vectors3) {
  61155. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  61156. }
  61157. // Vector4
  61158. for (name in source.vectors4) {
  61159. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  61160. }
  61161. // Matrix
  61162. for (name in source.matrices) {
  61163. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  61164. }
  61165. // Matrix 3x3
  61166. for (name in source.matrices3x3) {
  61167. material.setMatrix3x3(name, source.matrices3x3[name]);
  61168. }
  61169. // Matrix 2x2
  61170. for (name in source.matrices2x2) {
  61171. material.setMatrix2x2(name, source.matrices2x2[name]);
  61172. }
  61173. // Vector2Array
  61174. for (name in source.vectors2Arrays) {
  61175. material.setArray2(name, source.vectors2Arrays[name]);
  61176. }
  61177. // Vector3Array
  61178. for (name in source.vectors3Arrays) {
  61179. material.setArray3(name, source.vectors3Arrays[name]);
  61180. }
  61181. return material;
  61182. };
  61183. return ShaderMaterial;
  61184. }(BABYLON.Material));
  61185. BABYLON.ShaderMaterial = ShaderMaterial;
  61186. })(BABYLON || (BABYLON = {}));
  61187. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61188. var BABYLON;
  61189. (function (BABYLON) {
  61190. var GroundMesh = /** @class */ (function (_super) {
  61191. __extends(GroundMesh, _super);
  61192. function GroundMesh(name, scene) {
  61193. var _this = _super.call(this, name, scene) || this;
  61194. _this.generateOctree = false;
  61195. return _this;
  61196. }
  61197. GroundMesh.prototype.getClassName = function () {
  61198. return "GroundMesh";
  61199. };
  61200. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61201. get: function () {
  61202. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61203. },
  61204. enumerable: true,
  61205. configurable: true
  61206. });
  61207. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61208. get: function () {
  61209. return this._subdivisionsX;
  61210. },
  61211. enumerable: true,
  61212. configurable: true
  61213. });
  61214. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61215. get: function () {
  61216. return this._subdivisionsY;
  61217. },
  61218. enumerable: true,
  61219. configurable: true
  61220. });
  61221. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61222. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61223. this._subdivisionsX = chunksCount;
  61224. this._subdivisionsY = chunksCount;
  61225. this.subdivide(chunksCount);
  61226. // Call the octree system optimization if it is defined.
  61227. var thisAsAny = this;
  61228. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61229. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61230. }
  61231. };
  61232. /**
  61233. * Returns a height (y) value in the Worl system :
  61234. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61235. * Returns the ground y position if (x, z) are outside the ground surface.
  61236. */
  61237. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61238. var world = this.getWorldMatrix();
  61239. var invMat = BABYLON.Tmp.Matrix[5];
  61240. world.invertToRef(invMat);
  61241. var tmpVect = BABYLON.Tmp.Vector3[8];
  61242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61243. x = tmpVect.x;
  61244. z = tmpVect.z;
  61245. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61246. return this.position.y;
  61247. }
  61248. if (!this._heightQuads || this._heightQuads.length == 0) {
  61249. this._initHeightQuads();
  61250. this._computeHeightQuads();
  61251. }
  61252. var facet = this._getFacetAt(x, z);
  61253. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61254. // return y in the World system
  61255. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61256. return tmpVect.y;
  61257. };
  61258. /**
  61259. * Returns a normalized vector (Vector3) orthogonal to the ground
  61260. * at the ground coordinates (x, z) expressed in the World system.
  61261. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61262. */
  61263. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61264. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61265. this.getNormalAtCoordinatesToRef(x, z, normal);
  61266. return normal;
  61267. };
  61268. /**
  61269. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61270. * at the ground coordinates (x, z) expressed in the World system.
  61271. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61272. * Returns the GroundMesh.
  61273. */
  61274. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61275. var world = this.getWorldMatrix();
  61276. var tmpMat = BABYLON.Tmp.Matrix[5];
  61277. world.invertToRef(tmpMat);
  61278. var tmpVect = BABYLON.Tmp.Vector3[8];
  61279. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61280. x = tmpVect.x;
  61281. z = tmpVect.z;
  61282. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61283. return this;
  61284. }
  61285. if (!this._heightQuads || this._heightQuads.length == 0) {
  61286. this._initHeightQuads();
  61287. this._computeHeightQuads();
  61288. }
  61289. var facet = this._getFacetAt(x, z);
  61290. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61291. return this;
  61292. };
  61293. /**
  61294. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61295. * if the ground has been updated.
  61296. * This can be used in the render loop.
  61297. * Returns the GroundMesh.
  61298. */
  61299. GroundMesh.prototype.updateCoordinateHeights = function () {
  61300. if (!this._heightQuads || this._heightQuads.length == 0) {
  61301. this._initHeightQuads();
  61302. }
  61303. this._computeHeightQuads();
  61304. return this;
  61305. };
  61306. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61307. GroundMesh.prototype._getFacetAt = function (x, z) {
  61308. // retrieve col and row from x, z coordinates in the ground local system
  61309. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61310. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61311. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61312. var facet;
  61313. if (z < quad.slope.x * x + quad.slope.y) {
  61314. facet = quad.facet1;
  61315. }
  61316. else {
  61317. facet = quad.facet2;
  61318. }
  61319. return facet;
  61320. };
  61321. // Creates and populates the heightMap array with "facet" elements :
  61322. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61323. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61324. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61325. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61326. // Returns the GroundMesh.
  61327. GroundMesh.prototype._initHeightQuads = function () {
  61328. var subdivisionsX = this._subdivisionsX;
  61329. var subdivisionsY = this._subdivisionsY;
  61330. this._heightQuads = new Array();
  61331. for (var row = 0; row < subdivisionsY; row++) {
  61332. for (var col = 0; col < subdivisionsX; col++) {
  61333. 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) };
  61334. this._heightQuads[row * subdivisionsX + col] = quad;
  61335. }
  61336. }
  61337. return this;
  61338. };
  61339. // Compute each quad element values and update the the heightMap array :
  61340. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61341. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61342. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61343. // Returns the GroundMesh.
  61344. GroundMesh.prototype._computeHeightQuads = function () {
  61345. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61346. if (!positions) {
  61347. return this;
  61348. }
  61349. var v1 = BABYLON.Tmp.Vector3[3];
  61350. var v2 = BABYLON.Tmp.Vector3[2];
  61351. var v3 = BABYLON.Tmp.Vector3[1];
  61352. var v4 = BABYLON.Tmp.Vector3[0];
  61353. var v1v2 = BABYLON.Tmp.Vector3[4];
  61354. var v1v3 = BABYLON.Tmp.Vector3[5];
  61355. var v1v4 = BABYLON.Tmp.Vector3[6];
  61356. var norm1 = BABYLON.Tmp.Vector3[7];
  61357. var norm2 = BABYLON.Tmp.Vector3[8];
  61358. var i = 0;
  61359. var j = 0;
  61360. var k = 0;
  61361. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61362. var h = 0;
  61363. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61364. var d2 = 0;
  61365. var subdivisionsX = this._subdivisionsX;
  61366. var subdivisionsY = this._subdivisionsY;
  61367. for (var row = 0; row < subdivisionsY; row++) {
  61368. for (var col = 0; col < subdivisionsX; col++) {
  61369. i = col * 3;
  61370. j = row * (subdivisionsX + 1) * 3;
  61371. k = (row + 1) * (subdivisionsX + 1) * 3;
  61372. v1.x = positions[j + i];
  61373. v1.y = positions[j + i + 1];
  61374. v1.z = positions[j + i + 2];
  61375. v2.x = positions[j + i + 3];
  61376. v2.y = positions[j + i + 4];
  61377. v2.z = positions[j + i + 5];
  61378. v3.x = positions[k + i];
  61379. v3.y = positions[k + i + 1];
  61380. v3.z = positions[k + i + 2];
  61381. v4.x = positions[k + i + 3];
  61382. v4.y = positions[k + i + 4];
  61383. v4.z = positions[k + i + 5];
  61384. // 2D slope V1V4
  61385. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61386. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61387. // facet equations :
  61388. // we compute each facet normal vector
  61389. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61390. // we compute the value d by applying the equation to v1 which belongs to the plane
  61391. // then we store the facet equation in a Vector4
  61392. v2.subtractToRef(v1, v1v2);
  61393. v3.subtractToRef(v1, v1v3);
  61394. v4.subtractToRef(v1, v1v4);
  61395. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61396. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61397. norm1.normalize();
  61398. norm2.normalize();
  61399. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61400. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61401. var quad = this._heightQuads[row * subdivisionsX + col];
  61402. quad.slope.copyFromFloats(cd, h);
  61403. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61404. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61405. }
  61406. }
  61407. return this;
  61408. };
  61409. GroundMesh.prototype.serialize = function (serializationObject) {
  61410. _super.prototype.serialize.call(this, serializationObject);
  61411. serializationObject.subdivisionsX = this._subdivisionsX;
  61412. serializationObject.subdivisionsY = this._subdivisionsY;
  61413. serializationObject.minX = this._minX;
  61414. serializationObject.maxX = this._maxX;
  61415. serializationObject.minZ = this._minZ;
  61416. serializationObject.maxZ = this._maxZ;
  61417. serializationObject.width = this._width;
  61418. serializationObject.height = this._height;
  61419. };
  61420. GroundMesh.Parse = function (parsedMesh, scene) {
  61421. var result = new GroundMesh(parsedMesh.name, scene);
  61422. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61423. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61424. result._minX = parsedMesh.minX;
  61425. result._maxX = parsedMesh.maxX;
  61426. result._minZ = parsedMesh.minZ;
  61427. result._maxZ = parsedMesh.maxZ;
  61428. result._width = parsedMesh.width;
  61429. result._height = parsedMesh.height;
  61430. return result;
  61431. };
  61432. return GroundMesh;
  61433. }(BABYLON.Mesh));
  61434. BABYLON.GroundMesh = GroundMesh;
  61435. })(BABYLON || (BABYLON = {}));
  61436. //# sourceMappingURL=babylon.groundMesh.js.map
  61437. var BABYLON;
  61438. (function (BABYLON) {
  61439. /**
  61440. * Creates an instance based on a source mesh.
  61441. */
  61442. var InstancedMesh = /** @class */ (function (_super) {
  61443. __extends(InstancedMesh, _super);
  61444. function InstancedMesh(name, source) {
  61445. var _this = _super.call(this, name, source.getScene()) || this;
  61446. source.instances.push(_this);
  61447. _this._sourceMesh = source;
  61448. _this.position.copyFrom(source.position);
  61449. _this.rotation.copyFrom(source.rotation);
  61450. _this.scaling.copyFrom(source.scaling);
  61451. if (source.rotationQuaternion) {
  61452. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61453. }
  61454. _this.infiniteDistance = source.infiniteDistance;
  61455. _this.setPivotMatrix(source.getPivotMatrix());
  61456. _this.refreshBoundingInfo();
  61457. _this._syncSubMeshes();
  61458. return _this;
  61459. }
  61460. /**
  61461. * Returns the string "InstancedMesh".
  61462. */
  61463. InstancedMesh.prototype.getClassName = function () {
  61464. return "InstancedMesh";
  61465. };
  61466. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61467. // Methods
  61468. get: function () {
  61469. return this._sourceMesh.receiveShadows;
  61470. },
  61471. enumerable: true,
  61472. configurable: true
  61473. });
  61474. Object.defineProperty(InstancedMesh.prototype, "material", {
  61475. get: function () {
  61476. return this._sourceMesh.material;
  61477. },
  61478. enumerable: true,
  61479. configurable: true
  61480. });
  61481. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61482. get: function () {
  61483. return this._sourceMesh.visibility;
  61484. },
  61485. enumerable: true,
  61486. configurable: true
  61487. });
  61488. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61489. get: function () {
  61490. return this._sourceMesh.skeleton;
  61491. },
  61492. enumerable: true,
  61493. configurable: true
  61494. });
  61495. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61496. get: function () {
  61497. return this._sourceMesh.renderingGroupId;
  61498. },
  61499. set: function (value) {
  61500. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61501. return;
  61502. }
  61503. //no-op with warning
  61504. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61505. },
  61506. enumerable: true,
  61507. configurable: true
  61508. });
  61509. /**
  61510. * Returns the total number of vertices (integer).
  61511. */
  61512. InstancedMesh.prototype.getTotalVertices = function () {
  61513. return this._sourceMesh.getTotalVertices();
  61514. };
  61515. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61516. get: function () {
  61517. return this._sourceMesh;
  61518. },
  61519. enumerable: true,
  61520. configurable: true
  61521. });
  61522. /**
  61523. * Is this node ready to be used/rendered
  61524. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61525. * @return {boolean} is it ready
  61526. */
  61527. InstancedMesh.prototype.isReady = function (completeCheck) {
  61528. if (completeCheck === void 0) { completeCheck = false; }
  61529. return this._sourceMesh.isReady(completeCheck, true);
  61530. };
  61531. /**
  61532. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61533. */
  61534. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61535. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61536. };
  61537. /**
  61538. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61539. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61540. * The `data` are either a numeric array either a Float32Array.
  61541. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61542. * 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).
  61543. * Note that a new underlying VertexBuffer object is created each call.
  61544. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61545. *
  61546. * Possible `kind` values :
  61547. * - BABYLON.VertexBuffer.PositionKind
  61548. * - BABYLON.VertexBuffer.UVKind
  61549. * - BABYLON.VertexBuffer.UV2Kind
  61550. * - BABYLON.VertexBuffer.UV3Kind
  61551. * - BABYLON.VertexBuffer.UV4Kind
  61552. * - BABYLON.VertexBuffer.UV5Kind
  61553. * - BABYLON.VertexBuffer.UV6Kind
  61554. * - BABYLON.VertexBuffer.ColorKind
  61555. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61556. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61557. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61558. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61559. *
  61560. * Returns the Mesh.
  61561. */
  61562. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61563. if (this.sourceMesh) {
  61564. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61565. }
  61566. return this.sourceMesh;
  61567. };
  61568. /**
  61569. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61570. * If the mesh has no geometry, it is simply returned as it is.
  61571. * The `data` are either a numeric array either a Float32Array.
  61572. * No new underlying VertexBuffer object is created.
  61573. * 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.
  61574. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61575. *
  61576. * Possible `kind` values :
  61577. * - BABYLON.VertexBuffer.PositionKind
  61578. * - BABYLON.VertexBuffer.UVKind
  61579. * - BABYLON.VertexBuffer.UV2Kind
  61580. * - BABYLON.VertexBuffer.UV3Kind
  61581. * - BABYLON.VertexBuffer.UV4Kind
  61582. * - BABYLON.VertexBuffer.UV5Kind
  61583. * - BABYLON.VertexBuffer.UV6Kind
  61584. * - BABYLON.VertexBuffer.ColorKind
  61585. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61586. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61587. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61588. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61589. *
  61590. * Returns the Mesh.
  61591. */
  61592. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61593. if (this.sourceMesh) {
  61594. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61595. }
  61596. return this.sourceMesh;
  61597. };
  61598. /**
  61599. * Sets the mesh indices.
  61600. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61601. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61602. * This method creates a new index buffer each call.
  61603. * Returns the Mesh.
  61604. */
  61605. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61606. if (totalVertices === void 0) { totalVertices = null; }
  61607. if (this.sourceMesh) {
  61608. this.sourceMesh.setIndices(indices, totalVertices);
  61609. }
  61610. return this.sourceMesh;
  61611. };
  61612. /**
  61613. * Boolean : True if the mesh owns the requested kind of data.
  61614. */
  61615. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61616. return this._sourceMesh.isVerticesDataPresent(kind);
  61617. };
  61618. /**
  61619. * Returns an array of indices (IndicesArray).
  61620. */
  61621. InstancedMesh.prototype.getIndices = function () {
  61622. return this._sourceMesh.getIndices();
  61623. };
  61624. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61625. get: function () {
  61626. return this._sourceMesh._positions;
  61627. },
  61628. enumerable: true,
  61629. configurable: true
  61630. });
  61631. /**
  61632. * Sets a new updated BoundingInfo to the mesh.
  61633. * Returns the mesh.
  61634. */
  61635. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61636. var meshBB = this._sourceMesh.getBoundingInfo();
  61637. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61638. this._updateBoundingInfo();
  61639. return this;
  61640. };
  61641. /** @hidden */
  61642. InstancedMesh.prototype._preActivate = function () {
  61643. if (this._currentLOD) {
  61644. this._currentLOD._preActivate();
  61645. }
  61646. return this;
  61647. };
  61648. /** @hidden */
  61649. InstancedMesh.prototype._activate = function (renderId) {
  61650. if (this._currentLOD) {
  61651. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61652. }
  61653. return this;
  61654. };
  61655. /**
  61656. * Returns the current associated LOD AbstractMesh.
  61657. */
  61658. InstancedMesh.prototype.getLOD = function (camera) {
  61659. if (!camera) {
  61660. return this;
  61661. }
  61662. var boundingInfo = this.getBoundingInfo();
  61663. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61664. if (this._currentLOD === this.sourceMesh) {
  61665. return this;
  61666. }
  61667. return this._currentLOD;
  61668. };
  61669. /** @hidden */
  61670. InstancedMesh.prototype._syncSubMeshes = function () {
  61671. this.releaseSubMeshes();
  61672. if (this._sourceMesh.subMeshes) {
  61673. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61674. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61675. }
  61676. }
  61677. return this;
  61678. };
  61679. /** @hidden */
  61680. InstancedMesh.prototype._generatePointsArray = function () {
  61681. return this._sourceMesh._generatePointsArray();
  61682. };
  61683. /**
  61684. * Creates a new InstancedMesh from the current mesh.
  61685. * - name (string) : the cloned mesh name
  61686. * - newParent (optional Node) : the optional Node to parent the clone to.
  61687. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61688. *
  61689. * Returns the clone.
  61690. */
  61691. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61692. var result = this._sourceMesh.createInstance(name);
  61693. // Deep copy
  61694. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61695. // Bounding info
  61696. this.refreshBoundingInfo();
  61697. // Parent
  61698. if (newParent) {
  61699. result.parent = newParent;
  61700. }
  61701. if (!doNotCloneChildren) {
  61702. // Children
  61703. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61704. var mesh = this.getScene().meshes[index];
  61705. if (mesh.parent === this) {
  61706. mesh.clone(mesh.name, result);
  61707. }
  61708. }
  61709. }
  61710. result.computeWorldMatrix(true);
  61711. return result;
  61712. };
  61713. /**
  61714. * Disposes the InstancedMesh.
  61715. * Returns nothing.
  61716. */
  61717. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61718. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61719. // Remove from mesh
  61720. var index = this._sourceMesh.instances.indexOf(this);
  61721. this._sourceMesh.instances.splice(index, 1);
  61722. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61723. };
  61724. return InstancedMesh;
  61725. }(BABYLON.AbstractMesh));
  61726. BABYLON.InstancedMesh = InstancedMesh;
  61727. })(BABYLON || (BABYLON = {}));
  61728. //# sourceMappingURL=babylon.instancedMesh.js.map
  61729. var BABYLON;
  61730. (function (BABYLON) {
  61731. var LinesMesh = /** @class */ (function (_super) {
  61732. __extends(LinesMesh, _super);
  61733. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61734. if (scene === void 0) { scene = null; }
  61735. if (parent === void 0) { parent = null; }
  61736. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61737. _this.useVertexColor = useVertexColor;
  61738. _this.useVertexAlpha = useVertexAlpha;
  61739. _this.color = new BABYLON.Color3(1, 1, 1);
  61740. _this.alpha = 1;
  61741. if (source) {
  61742. _this.color = source.color.clone();
  61743. _this.alpha = source.alpha;
  61744. _this.useVertexColor = source.useVertexColor;
  61745. _this.useVertexAlpha = source.useVertexAlpha;
  61746. }
  61747. _this._intersectionThreshold = 0.1;
  61748. var defines = [];
  61749. var options = {
  61750. attributes: [BABYLON.VertexBuffer.PositionKind],
  61751. uniforms: ["world", "viewProjection"],
  61752. needAlphaBlending: true,
  61753. defines: defines
  61754. };
  61755. if (useVertexAlpha === false) {
  61756. options.needAlphaBlending = false;
  61757. }
  61758. if (!useVertexColor) {
  61759. options.uniforms.push("color");
  61760. }
  61761. else {
  61762. options.defines.push("#define VERTEXCOLOR");
  61763. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61764. }
  61765. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61766. return _this;
  61767. }
  61768. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61769. /**
  61770. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61771. * This margin is expressed in world space coordinates, so its value may vary.
  61772. * Default value is 0.1
  61773. * @returns the intersection Threshold value.
  61774. */
  61775. get: function () {
  61776. return this._intersectionThreshold;
  61777. },
  61778. /**
  61779. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61780. * This margin is expressed in world space coordinates, so its value may vary.
  61781. * @param value the new threshold to apply
  61782. */
  61783. set: function (value) {
  61784. if (this._intersectionThreshold === value) {
  61785. return;
  61786. }
  61787. this._intersectionThreshold = value;
  61788. if (this.geometry) {
  61789. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61790. }
  61791. },
  61792. enumerable: true,
  61793. configurable: true
  61794. });
  61795. /**
  61796. * Returns the string "LineMesh"
  61797. */
  61798. LinesMesh.prototype.getClassName = function () {
  61799. return "LinesMesh";
  61800. };
  61801. Object.defineProperty(LinesMesh.prototype, "material", {
  61802. /**
  61803. * @hidden
  61804. */
  61805. get: function () {
  61806. return this._colorShader;
  61807. },
  61808. /**
  61809. * @hidden
  61810. */
  61811. set: function (value) {
  61812. // Do nothing
  61813. },
  61814. enumerable: true,
  61815. configurable: true
  61816. });
  61817. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61818. /**
  61819. * @hidden
  61820. */
  61821. get: function () {
  61822. return false;
  61823. },
  61824. enumerable: true,
  61825. configurable: true
  61826. });
  61827. LinesMesh.prototype.createInstance = function (name) {
  61828. throw new Error("LinesMeshes do not support createInstance.");
  61829. };
  61830. /** @hidden */
  61831. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61832. if (!this._geometry) {
  61833. return this;
  61834. }
  61835. // VBOs
  61836. this._geometry._bind(this._colorShader.getEffect());
  61837. // Color
  61838. if (!this.useVertexColor) {
  61839. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61840. }
  61841. return this;
  61842. };
  61843. /** @hidden */
  61844. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61845. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61846. return this;
  61847. }
  61848. var engine = this.getScene().getEngine();
  61849. // Draw order
  61850. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61851. return this;
  61852. };
  61853. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61854. this._colorShader.dispose();
  61855. _super.prototype.dispose.call(this, doNotRecurse);
  61856. };
  61857. /**
  61858. * Returns a new LineMesh object cloned from the current one.
  61859. */
  61860. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61861. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61862. };
  61863. return LinesMesh;
  61864. }(BABYLON.Mesh));
  61865. BABYLON.LinesMesh = LinesMesh;
  61866. })(BABYLON || (BABYLON = {}));
  61867. //# sourceMappingURL=babylon.linesMesh.js.map
  61868. var BABYLON;
  61869. (function (BABYLON) {
  61870. /**
  61871. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61872. * The underlying implementation relies on an associative array to ensure the best performances.
  61873. * The value can be anything including 'null' but except 'undefined'
  61874. */
  61875. var StringDictionary = /** @class */ (function () {
  61876. function StringDictionary() {
  61877. this._count = 0;
  61878. this._data = {};
  61879. }
  61880. /**
  61881. * This will clear this dictionary and copy the content from the 'source' one.
  61882. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61883. * @param source the dictionary to take the content from and copy to this dictionary
  61884. */
  61885. StringDictionary.prototype.copyFrom = function (source) {
  61886. var _this = this;
  61887. this.clear();
  61888. source.forEach(function (t, v) { return _this.add(t, v); });
  61889. };
  61890. /**
  61891. * Get a value based from its key
  61892. * @param key the given key to get the matching value from
  61893. * @return the value if found, otherwise undefined is returned
  61894. */
  61895. StringDictionary.prototype.get = function (key) {
  61896. var val = this._data[key];
  61897. if (val !== undefined) {
  61898. return val;
  61899. }
  61900. return undefined;
  61901. };
  61902. /**
  61903. * Get a value from its key or add it if it doesn't exist.
  61904. * This method will ensure you that a given key/data will be present in the dictionary.
  61905. * @param key the given key to get the matching value from
  61906. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61907. * The factory will only be invoked if there's no data for the given key.
  61908. * @return the value corresponding to the key.
  61909. */
  61910. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61911. var val = this.get(key);
  61912. if (val !== undefined) {
  61913. return val;
  61914. }
  61915. val = factory(key);
  61916. if (val) {
  61917. this.add(key, val);
  61918. }
  61919. return val;
  61920. };
  61921. /**
  61922. * Get a value from its key if present in the dictionary otherwise add it
  61923. * @param key the key to get the value from
  61924. * @param val if there's no such key/value pair in the dictionary add it with this value
  61925. * @return the value corresponding to the key
  61926. */
  61927. StringDictionary.prototype.getOrAdd = function (key, val) {
  61928. var curVal = this.get(key);
  61929. if (curVal !== undefined) {
  61930. return curVal;
  61931. }
  61932. this.add(key, val);
  61933. return val;
  61934. };
  61935. /**
  61936. * Check if there's a given key in the dictionary
  61937. * @param key the key to check for
  61938. * @return true if the key is present, false otherwise
  61939. */
  61940. StringDictionary.prototype.contains = function (key) {
  61941. return this._data[key] !== undefined;
  61942. };
  61943. /**
  61944. * Add a new key and its corresponding value
  61945. * @param key the key to add
  61946. * @param value the value corresponding to the key
  61947. * @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
  61948. */
  61949. StringDictionary.prototype.add = function (key, value) {
  61950. if (this._data[key] !== undefined) {
  61951. return false;
  61952. }
  61953. this._data[key] = value;
  61954. ++this._count;
  61955. return true;
  61956. };
  61957. StringDictionary.prototype.set = function (key, value) {
  61958. if (this._data[key] === undefined) {
  61959. return false;
  61960. }
  61961. this._data[key] = value;
  61962. return true;
  61963. };
  61964. /**
  61965. * Get the element of the given key and remove it from the dictionary
  61966. * @param key
  61967. */
  61968. StringDictionary.prototype.getAndRemove = function (key) {
  61969. var val = this.get(key);
  61970. if (val !== undefined) {
  61971. delete this._data[key];
  61972. --this._count;
  61973. return val;
  61974. }
  61975. return null;
  61976. };
  61977. /**
  61978. * Remove a key/value from the dictionary.
  61979. * @param key the key to remove
  61980. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61981. */
  61982. StringDictionary.prototype.remove = function (key) {
  61983. if (this.contains(key)) {
  61984. delete this._data[key];
  61985. --this._count;
  61986. return true;
  61987. }
  61988. return false;
  61989. };
  61990. /**
  61991. * Clear the whole content of the dictionary
  61992. */
  61993. StringDictionary.prototype.clear = function () {
  61994. this._data = {};
  61995. this._count = 0;
  61996. };
  61997. Object.defineProperty(StringDictionary.prototype, "count", {
  61998. get: function () {
  61999. return this._count;
  62000. },
  62001. enumerable: true,
  62002. configurable: true
  62003. });
  62004. /**
  62005. * Execute a callback on each key/val of the dictionary.
  62006. * Note that you can remove any element in this dictionary in the callback implementation
  62007. * @param callback the callback to execute on a given key/value pair
  62008. */
  62009. StringDictionary.prototype.forEach = function (callback) {
  62010. for (var cur in this._data) {
  62011. var val = this._data[cur];
  62012. callback(cur, val);
  62013. }
  62014. };
  62015. /**
  62016. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62017. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62018. * Note that you can remove any element in this dictionary in the callback implementation
  62019. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62020. */
  62021. StringDictionary.prototype.first = function (callback) {
  62022. for (var cur in this._data) {
  62023. var val = this._data[cur];
  62024. var res = callback(cur, val);
  62025. if (res) {
  62026. return res;
  62027. }
  62028. }
  62029. return null;
  62030. };
  62031. return StringDictionary;
  62032. }());
  62033. BABYLON.StringDictionary = StringDictionary;
  62034. })(BABYLON || (BABYLON = {}));
  62035. //# sourceMappingURL=babylon.stringDictionary.js.map
  62036. var BABYLON;
  62037. (function (BABYLON) {
  62038. var Debug;
  62039. (function (Debug) {
  62040. /**
  62041. * Class used to render a debug view of a given skeleton
  62042. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62043. */
  62044. var SkeletonViewer = /** @class */ (function () {
  62045. /**
  62046. * Creates a new SkeletonViewer
  62047. * @param skeleton defines the skeleton to render
  62048. * @param mesh defines the mesh attached to the skeleton
  62049. * @param scene defines the hosting scene
  62050. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62051. * @param renderingGroupId defines the rendering group id to use with the viewer
  62052. */
  62053. function SkeletonViewer(
  62054. /** defines the skeleton to render */
  62055. skeleton,
  62056. /** defines the mesh attached to the skeleton */
  62057. mesh, scene,
  62058. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62059. autoUpdateBonesMatrices,
  62060. /** defines the rendering group id to use with the viewer */
  62061. renderingGroupId) {
  62062. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62063. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62064. this.skeleton = skeleton;
  62065. this.mesh = mesh;
  62066. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62067. this.renderingGroupId = renderingGroupId;
  62068. /** Gets or sets the color used to render the skeleton */
  62069. this.color = BABYLON.Color3.White();
  62070. this._debugLines = new Array();
  62071. this._isEnabled = false;
  62072. this._scene = scene;
  62073. this.update();
  62074. this._renderFunction = this.update.bind(this);
  62075. }
  62076. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62077. get: function () {
  62078. return this._isEnabled;
  62079. },
  62080. /** Gets or sets a boolean indicating if the viewer is enabled */
  62081. set: function (value) {
  62082. if (this._isEnabled === value) {
  62083. return;
  62084. }
  62085. this._isEnabled = value;
  62086. if (value) {
  62087. this._scene.registerBeforeRender(this._renderFunction);
  62088. }
  62089. else {
  62090. this._scene.unregisterBeforeRender(this._renderFunction);
  62091. }
  62092. },
  62093. enumerable: true,
  62094. configurable: true
  62095. });
  62096. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62097. if (x === void 0) { x = 0; }
  62098. if (y === void 0) { y = 0; }
  62099. if (z === void 0) { z = 0; }
  62100. var tmat = BABYLON.Tmp.Matrix[0];
  62101. var parentBone = bone.getParent();
  62102. tmat.copyFrom(bone.getLocalMatrix());
  62103. if (x !== 0 || y !== 0 || z !== 0) {
  62104. var tmat2 = BABYLON.Tmp.Matrix[1];
  62105. BABYLON.Matrix.IdentityToRef(tmat2);
  62106. tmat2.m[12] = x;
  62107. tmat2.m[13] = y;
  62108. tmat2.m[14] = z;
  62109. tmat2.multiplyToRef(tmat, tmat);
  62110. }
  62111. if (parentBone) {
  62112. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62113. }
  62114. tmat.multiplyToRef(meshMat, tmat);
  62115. position.x = tmat.m[12];
  62116. position.y = tmat.m[13];
  62117. position.z = tmat.m[14];
  62118. };
  62119. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62120. var len = bones.length;
  62121. var meshPos = this.mesh.position;
  62122. for (var i = 0; i < len; i++) {
  62123. var bone = bones[i];
  62124. var points = this._debugLines[i];
  62125. if (!points) {
  62126. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62127. this._debugLines[i] = points;
  62128. }
  62129. this._getBonePosition(points[0], bone, meshMat);
  62130. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62131. points[0].subtractInPlace(meshPos);
  62132. points[1].subtractInPlace(meshPos);
  62133. }
  62134. };
  62135. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62136. var len = bones.length;
  62137. var boneNum = 0;
  62138. var meshPos = this.mesh.position;
  62139. for (var i = len - 1; i >= 0; i--) {
  62140. var childBone = bones[i];
  62141. var parentBone = childBone.getParent();
  62142. if (!parentBone) {
  62143. continue;
  62144. }
  62145. var points = this._debugLines[boneNum];
  62146. if (!points) {
  62147. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62148. this._debugLines[boneNum] = points;
  62149. }
  62150. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62151. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62152. points[0].subtractInPlace(meshPos);
  62153. points[1].subtractInPlace(meshPos);
  62154. boneNum++;
  62155. }
  62156. };
  62157. /** Update the viewer to sync with current skeleton state */
  62158. SkeletonViewer.prototype.update = function () {
  62159. if (this.autoUpdateBonesMatrices) {
  62160. this.skeleton.computeAbsoluteTransforms();
  62161. }
  62162. if (this.skeleton.bones[0].length === undefined) {
  62163. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62164. }
  62165. else {
  62166. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62167. }
  62168. if (!this._debugMesh) {
  62169. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  62170. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62171. }
  62172. else {
  62173. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62174. }
  62175. this._debugMesh.position.copyFrom(this.mesh.position);
  62176. this._debugMesh.color = this.color;
  62177. };
  62178. /** Release associated resources */
  62179. SkeletonViewer.prototype.dispose = function () {
  62180. if (this._debugMesh) {
  62181. this.isEnabled = false;
  62182. this._debugMesh.dispose();
  62183. this._debugMesh = null;
  62184. }
  62185. };
  62186. return SkeletonViewer;
  62187. }());
  62188. Debug.SkeletonViewer = SkeletonViewer;
  62189. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62190. })(BABYLON || (BABYLON = {}));
  62191. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62192. /**
  62193. * Module Debug contains the (visual) components to debug a scene correctly
  62194. */
  62195. var BABYLON;
  62196. (function (BABYLON) {
  62197. var Debug;
  62198. (function (Debug) {
  62199. /**
  62200. * The Axes viewer will show 3 axes in a specific point in space
  62201. */
  62202. var AxesViewer = /** @class */ (function () {
  62203. /**
  62204. * Creates a new AxesViewer
  62205. * @param scene defines the hosting scene
  62206. * @param scaleLines defines a number used to scale line length (1 by default)
  62207. */
  62208. function AxesViewer(scene, scaleLines) {
  62209. if (scaleLines === void 0) { scaleLines = 1; }
  62210. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62211. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62212. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62213. /**
  62214. * Gets or sets a number used to scale line length
  62215. */
  62216. this.scaleLines = 1;
  62217. this.scaleLines = scaleLines;
  62218. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62219. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62220. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62221. this._xmesh.renderingGroupId = 2;
  62222. this._ymesh.renderingGroupId = 2;
  62223. this._zmesh.renderingGroupId = 2;
  62224. this._xmesh.material.checkReadyOnlyOnce = true;
  62225. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62226. this._ymesh.material.checkReadyOnlyOnce = true;
  62227. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62228. this._zmesh.material.checkReadyOnlyOnce = true;
  62229. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62230. this.scene = scene;
  62231. }
  62232. /**
  62233. * Force the viewer to update
  62234. * @param position defines the position of the viewer
  62235. * @param xaxis defines the x axis of the viewer
  62236. * @param yaxis defines the y axis of the viewer
  62237. * @param zaxis defines the z axis of the viewer
  62238. */
  62239. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62240. var scaleLines = this.scaleLines;
  62241. if (this._xmesh) {
  62242. this._xmesh.position.copyFrom(position);
  62243. }
  62244. if (this._ymesh) {
  62245. this._ymesh.position.copyFrom(position);
  62246. }
  62247. if (this._zmesh) {
  62248. this._zmesh.position.copyFrom(position);
  62249. }
  62250. var point2 = this._xline[1];
  62251. point2.x = xaxis.x * scaleLines;
  62252. point2.y = xaxis.y * scaleLines;
  62253. point2.z = xaxis.z * scaleLines;
  62254. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62255. point2 = this._yline[1];
  62256. point2.x = yaxis.x * scaleLines;
  62257. point2.y = yaxis.y * scaleLines;
  62258. point2.z = yaxis.z * scaleLines;
  62259. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62260. point2 = this._zline[1];
  62261. point2.x = zaxis.x * scaleLines;
  62262. point2.y = zaxis.y * scaleLines;
  62263. point2.z = zaxis.z * scaleLines;
  62264. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62265. };
  62266. /** Releases resources */
  62267. AxesViewer.prototype.dispose = function () {
  62268. if (this._xmesh) {
  62269. this._xmesh.dispose();
  62270. }
  62271. if (this._ymesh) {
  62272. this._ymesh.dispose();
  62273. }
  62274. if (this._zmesh) {
  62275. this._zmesh.dispose();
  62276. }
  62277. this._xmesh = null;
  62278. this._ymesh = null;
  62279. this._zmesh = null;
  62280. this.scene = null;
  62281. };
  62282. return AxesViewer;
  62283. }());
  62284. Debug.AxesViewer = AxesViewer;
  62285. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62286. })(BABYLON || (BABYLON = {}));
  62287. //# sourceMappingURL=babylon.axesViewer.js.map
  62288. var BABYLON;
  62289. (function (BABYLON) {
  62290. var Debug;
  62291. (function (Debug) {
  62292. /**
  62293. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62294. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62295. */
  62296. var BoneAxesViewer = /** @class */ (function (_super) {
  62297. __extends(BoneAxesViewer, _super);
  62298. /**
  62299. * Creates a new BoneAxesViewer
  62300. * @param scene defines the hosting scene
  62301. * @param bone defines the target bone
  62302. * @param mesh defines the target mesh
  62303. * @param scaleLines defines a scaling factor for line length (1 by default)
  62304. */
  62305. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62306. if (scaleLines === void 0) { scaleLines = 1; }
  62307. var _this = _super.call(this, scene, scaleLines) || this;
  62308. /** Gets current position */
  62309. _this.pos = BABYLON.Vector3.Zero();
  62310. /** Gets direction of X axis */
  62311. _this.xaxis = BABYLON.Vector3.Zero();
  62312. /** Gets direction of Y axis */
  62313. _this.yaxis = BABYLON.Vector3.Zero();
  62314. /** Gets direction of Z axis */
  62315. _this.zaxis = BABYLON.Vector3.Zero();
  62316. _this.mesh = mesh;
  62317. _this.bone = bone;
  62318. return _this;
  62319. }
  62320. /**
  62321. * Force the viewer to update
  62322. */
  62323. BoneAxesViewer.prototype.update = function () {
  62324. if (!this.mesh || !this.bone) {
  62325. return;
  62326. }
  62327. var bone = this.bone;
  62328. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62329. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62330. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62331. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62332. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62333. };
  62334. /** Releases resources */
  62335. BoneAxesViewer.prototype.dispose = function () {
  62336. if (this.mesh) {
  62337. this.mesh = null;
  62338. this.bone = null;
  62339. _super.prototype.dispose.call(this);
  62340. }
  62341. };
  62342. return BoneAxesViewer;
  62343. }(Debug.AxesViewer));
  62344. Debug.BoneAxesViewer = BoneAxesViewer;
  62345. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62346. })(BABYLON || (BABYLON = {}));
  62347. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62348. var BABYLON;
  62349. (function (BABYLON) {
  62350. /**
  62351. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62352. * in order to better appreciate the issue one might have.
  62353. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62354. */
  62355. var RayHelper = /** @class */ (function () {
  62356. /**
  62357. * Instantiate a new ray helper.
  62358. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62359. * in order to better appreciate the issue one might have.
  62360. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62361. * @param ray Defines the ray we are currently tryin to visualize
  62362. */
  62363. function RayHelper(ray) {
  62364. this.ray = ray;
  62365. }
  62366. /**
  62367. * Helper function to create a colored helper in a scene in one line.
  62368. * @param ray Defines the ray we are currently tryin to visualize
  62369. * @param scene Defines the scene the ray is used in
  62370. * @param color Defines the color we want to see the ray in
  62371. * @returns The newly created ray helper.
  62372. */
  62373. RayHelper.CreateAndShow = function (ray, scene, color) {
  62374. var helper = new RayHelper(ray);
  62375. helper.show(scene, color);
  62376. return helper;
  62377. };
  62378. /**
  62379. * Shows the ray we are willing to debug.
  62380. * @param scene Defines the scene the ray needs to be rendered in
  62381. * @param color Defines the color the ray needs to be rendered in
  62382. */
  62383. RayHelper.prototype.show = function (scene, color) {
  62384. if (!this._renderFunction && this.ray) {
  62385. var ray = this.ray;
  62386. this._renderFunction = this._render.bind(this);
  62387. this._scene = scene;
  62388. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62389. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62390. if (this._renderFunction) {
  62391. this._scene.registerBeforeRender(this._renderFunction);
  62392. }
  62393. }
  62394. if (color && this._renderLine) {
  62395. this._renderLine.color.copyFrom(color);
  62396. }
  62397. };
  62398. /**
  62399. * Hides the ray we are debugging.
  62400. */
  62401. RayHelper.prototype.hide = function () {
  62402. if (this._renderFunction && this._scene) {
  62403. this._scene.unregisterBeforeRender(this._renderFunction);
  62404. this._scene = null;
  62405. this._renderFunction = null;
  62406. if (this._renderLine) {
  62407. this._renderLine.dispose();
  62408. this._renderLine = null;
  62409. }
  62410. this._renderPoints = [];
  62411. }
  62412. };
  62413. RayHelper.prototype._render = function () {
  62414. var ray = this.ray;
  62415. if (!ray) {
  62416. return;
  62417. }
  62418. var point = this._renderPoints[1];
  62419. var len = Math.min(ray.length, 1000000);
  62420. point.copyFrom(ray.direction);
  62421. point.scaleInPlace(len);
  62422. point.addInPlace(ray.origin);
  62423. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62424. };
  62425. /**
  62426. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  62427. * @param mesh Defines the mesh we want the helper attached to
  62428. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  62429. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  62430. * @param length Defines the length of the ray
  62431. */
  62432. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62433. this._attachedToMesh = mesh;
  62434. var ray = this.ray;
  62435. if (!ray) {
  62436. return;
  62437. }
  62438. if (!ray.direction) {
  62439. ray.direction = BABYLON.Vector3.Zero();
  62440. }
  62441. if (!ray.origin) {
  62442. ray.origin = BABYLON.Vector3.Zero();
  62443. }
  62444. if (length) {
  62445. ray.length = length;
  62446. }
  62447. if (!meshSpaceOrigin) {
  62448. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62449. }
  62450. if (!meshSpaceDirection) {
  62451. // -1 so that this will work with Mesh.lookAt
  62452. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62453. }
  62454. if (!this._meshSpaceDirection) {
  62455. this._meshSpaceDirection = meshSpaceDirection.clone();
  62456. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62457. }
  62458. else {
  62459. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62460. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62461. }
  62462. if (!this._updateToMeshFunction) {
  62463. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62464. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62465. }
  62466. this._updateToMesh();
  62467. };
  62468. /**
  62469. * Detach the ray helper from the mesh it has previously been attached to.
  62470. */
  62471. RayHelper.prototype.detachFromMesh = function () {
  62472. if (this._attachedToMesh) {
  62473. if (this._updateToMeshFunction) {
  62474. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62475. }
  62476. this._attachedToMesh = null;
  62477. this._updateToMeshFunction = null;
  62478. }
  62479. };
  62480. RayHelper.prototype._updateToMesh = function () {
  62481. var ray = this.ray;
  62482. if (!this._attachedToMesh || !ray) {
  62483. return;
  62484. }
  62485. if (this._attachedToMesh._isDisposed) {
  62486. this.detachFromMesh();
  62487. return;
  62488. }
  62489. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62490. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62491. };
  62492. /**
  62493. * Dispose the helper and release its associated resources.
  62494. */
  62495. RayHelper.prototype.dispose = function () {
  62496. this.hide();
  62497. this.detachFromMesh();
  62498. this.ray = null;
  62499. };
  62500. return RayHelper;
  62501. }());
  62502. BABYLON.RayHelper = RayHelper;
  62503. })(BABYLON || (BABYLON = {}));
  62504. //# sourceMappingURL=babylon.rayHelper.js.map
  62505. var BABYLON;
  62506. (function (BABYLON) {
  62507. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62508. get: function () {
  62509. if (!this._debugLayer) {
  62510. this._debugLayer = new DebugLayer(this);
  62511. }
  62512. return this._debugLayer;
  62513. },
  62514. enumerable: true,
  62515. configurable: true
  62516. });
  62517. /**
  62518. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62519. * what is happening in your scene
  62520. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62521. */
  62522. var DebugLayer = /** @class */ (function () {
  62523. /**
  62524. * Instantiates a new debug layer.
  62525. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62526. * what is happening in your scene
  62527. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62528. * @param scene Defines the scene to inspect
  62529. */
  62530. function DebugLayer(scene) {
  62531. var _this = this;
  62532. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62533. /**
  62534. * Observable triggered when a property is changed through the inspector.
  62535. */
  62536. this.onPropertyChangedObservable = new BABYLON.Observable();
  62537. this._scene = scene;
  62538. this._scene.onDisposeObservable.add(function () {
  62539. // Debug layer
  62540. if (_this._scene._debugLayer) {
  62541. _this._scene._debugLayer.hide();
  62542. }
  62543. });
  62544. }
  62545. /** Creates the inspector window. */
  62546. DebugLayer.prototype._createInspector = function (config) {
  62547. if (config === void 0) { config = {}; }
  62548. var popup = config.popup || false;
  62549. var initialTab = config.initialTab || 0;
  62550. var parentElement = config.parentElement || null;
  62551. if (!this._inspector) {
  62552. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62553. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62554. } // else nothing to do as instance is already created
  62555. };
  62556. /**
  62557. * Get if the inspector is visible or not.
  62558. * @returns true if visible otherwise, false
  62559. */
  62560. DebugLayer.prototype.isVisible = function () {
  62561. if (!this._inspector) {
  62562. return false;
  62563. }
  62564. return true;
  62565. };
  62566. /**
  62567. * Hide the inspector and close its window.
  62568. */
  62569. DebugLayer.prototype.hide = function () {
  62570. if (this._inspector) {
  62571. try {
  62572. this._inspector.dispose();
  62573. }
  62574. catch (e) {
  62575. // If the inspector has been removed directly from the inspector tool
  62576. }
  62577. this.onPropertyChangedObservable.clear();
  62578. this._inspector = null;
  62579. }
  62580. };
  62581. /**
  62582. *
  62583. * Launch the debugLayer.
  62584. *
  62585. * initialTab:
  62586. * | Value | Tab Name |
  62587. * | --- | --- |
  62588. * | 0 | Scene |
  62589. * | 1 | Console |
  62590. * | 2 | Stats |
  62591. * | 3 | Textures |
  62592. * | 4 | Mesh |
  62593. * | 5 | Light |
  62594. * | 6 | Material |
  62595. * | 7 | GLTF |
  62596. * | 8 | GUI |
  62597. * | 9 | Physics |
  62598. * | 10 | Camera |
  62599. * | 11 | Audio |
  62600. *
  62601. * @param config Define the configuration of the inspector
  62602. */
  62603. DebugLayer.prototype.show = function (config) {
  62604. if (config === void 0) { config = {}; }
  62605. if (typeof this.BJSINSPECTOR == 'undefined') {
  62606. // Load inspector and add it to the DOM
  62607. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62608. }
  62609. else {
  62610. // Otherwise creates the inspector
  62611. this._createInspector(config);
  62612. }
  62613. };
  62614. /**
  62615. * Gets the active tab
  62616. * @return the index of the active tab or -1 if the inspector is hidden
  62617. */
  62618. DebugLayer.prototype.getActiveTab = function () {
  62619. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62620. };
  62621. /**
  62622. * Define the url to get the inspector script from.
  62623. * By default it uses the babylonjs CDN.
  62624. * @ignoreNaming
  62625. */
  62626. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62627. return DebugLayer;
  62628. }());
  62629. BABYLON.DebugLayer = DebugLayer;
  62630. })(BABYLON || (BABYLON = {}));
  62631. //# sourceMappingURL=babylon.debugLayer.js.map
  62632. var BABYLON;
  62633. (function (BABYLON) {
  62634. var Debug;
  62635. (function (Debug) {
  62636. /**
  62637. * Used to show the physics impostor around the specific mesh
  62638. */
  62639. var PhysicsViewer = /** @class */ (function () {
  62640. /**
  62641. * Creates a new PhysicsViewer
  62642. * @param scene defines the hosting scene
  62643. */
  62644. function PhysicsViewer(scene) {
  62645. /** @hidden */
  62646. this._impostors = [];
  62647. /** @hidden */
  62648. this._meshes = [];
  62649. /** @hidden */
  62650. this._numMeshes = 0;
  62651. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62652. var physicEngine = this._scene.getPhysicsEngine();
  62653. if (physicEngine) {
  62654. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62655. }
  62656. }
  62657. /** @hidden */
  62658. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62659. var plugin = this._physicsEnginePlugin;
  62660. for (var i = 0; i < this._numMeshes; i++) {
  62661. var impostor = this._impostors[i];
  62662. if (!impostor) {
  62663. continue;
  62664. }
  62665. if (impostor.isDisposed) {
  62666. this.hideImpostor(this._impostors[i--]);
  62667. }
  62668. else {
  62669. var mesh = this._meshes[i];
  62670. if (mesh && plugin) {
  62671. plugin.syncMeshWithImpostor(mesh, impostor);
  62672. }
  62673. }
  62674. }
  62675. };
  62676. /**
  62677. * Renders a specified physic impostor
  62678. * @param impostor defines the impostor to render
  62679. */
  62680. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62681. if (!this._scene) {
  62682. return;
  62683. }
  62684. for (var i = 0; i < this._numMeshes; i++) {
  62685. if (this._impostors[i] == impostor) {
  62686. return;
  62687. }
  62688. }
  62689. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62690. if (debugMesh) {
  62691. this._impostors[this._numMeshes] = impostor;
  62692. this._meshes[this._numMeshes] = debugMesh;
  62693. if (this._numMeshes === 0) {
  62694. this._renderFunction = this._updateDebugMeshes.bind(this);
  62695. this._scene.registerBeforeRender(this._renderFunction);
  62696. }
  62697. this._numMeshes++;
  62698. }
  62699. };
  62700. /**
  62701. * Hides a specified physic impostor
  62702. * @param impostor defines the impostor to hide
  62703. */
  62704. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62705. if (!impostor || !this._scene) {
  62706. return;
  62707. }
  62708. var removed = false;
  62709. for (var i = 0; i < this._numMeshes; i++) {
  62710. if (this._impostors[i] == impostor) {
  62711. var mesh = this._meshes[i];
  62712. if (!mesh) {
  62713. continue;
  62714. }
  62715. this._scene.removeMesh(mesh);
  62716. mesh.dispose();
  62717. this._numMeshes--;
  62718. if (this._numMeshes > 0) {
  62719. this._meshes[i] = this._meshes[this._numMeshes];
  62720. this._impostors[i] = this._impostors[this._numMeshes];
  62721. this._meshes[this._numMeshes] = null;
  62722. this._impostors[this._numMeshes] = null;
  62723. }
  62724. else {
  62725. this._meshes[0] = null;
  62726. this._impostors[0] = null;
  62727. }
  62728. removed = true;
  62729. break;
  62730. }
  62731. }
  62732. if (removed && this._numMeshes === 0) {
  62733. this._scene.unregisterBeforeRender(this._renderFunction);
  62734. }
  62735. };
  62736. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62737. if (!this._debugMaterial) {
  62738. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62739. this._debugMaterial.wireframe = true;
  62740. }
  62741. return this._debugMaterial;
  62742. };
  62743. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62744. if (!this._debugBoxMesh) {
  62745. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62746. this._debugBoxMesh.renderingGroupId = 1;
  62747. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62748. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62749. scene.removeMesh(this._debugBoxMesh);
  62750. }
  62751. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62752. };
  62753. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62754. if (!this._debugSphereMesh) {
  62755. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62756. this._debugSphereMesh.renderingGroupId = 1;
  62757. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62758. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62759. scene.removeMesh(this._debugSphereMesh);
  62760. }
  62761. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62762. };
  62763. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62764. var mesh = null;
  62765. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62766. mesh = this._getDebugBoxMesh(scene);
  62767. impostor.getBoxSizeToRef(mesh.scaling);
  62768. }
  62769. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62770. mesh = this._getDebugSphereMesh(scene);
  62771. var radius = impostor.getRadius();
  62772. mesh.scaling.x = radius * 2;
  62773. mesh.scaling.y = radius * 2;
  62774. mesh.scaling.z = radius * 2;
  62775. }
  62776. return mesh;
  62777. };
  62778. /** Releases all resources */
  62779. PhysicsViewer.prototype.dispose = function () {
  62780. for (var i = 0; i < this._numMeshes; i++) {
  62781. this.hideImpostor(this._impostors[i]);
  62782. }
  62783. if (this._debugBoxMesh) {
  62784. this._debugBoxMesh.dispose();
  62785. }
  62786. if (this._debugSphereMesh) {
  62787. this._debugSphereMesh.dispose();
  62788. }
  62789. if (this._debugMaterial) {
  62790. this._debugMaterial.dispose();
  62791. }
  62792. this._impostors.length = 0;
  62793. this._scene = null;
  62794. this._physicsEnginePlugin = null;
  62795. };
  62796. return PhysicsViewer;
  62797. }());
  62798. Debug.PhysicsViewer = PhysicsViewer;
  62799. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62800. })(BABYLON || (BABYLON = {}));
  62801. //# sourceMappingURL=babylon.physicsViewer.js.map
  62802. var BABYLON;
  62803. (function (BABYLON) {
  62804. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62805. get: function () {
  62806. return this._forceShowBoundingBoxes || false;
  62807. },
  62808. set: function (value) {
  62809. this._forceShowBoundingBoxes = value;
  62810. // Lazyly creates a BB renderer if needed.
  62811. if (value) {
  62812. this.getBoundingBoxRenderer();
  62813. }
  62814. },
  62815. enumerable: true,
  62816. configurable: true
  62817. });
  62818. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62819. if (!this._boundingBoxRenderer) {
  62820. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62821. }
  62822. return this._boundingBoxRenderer;
  62823. };
  62824. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62825. get: function () {
  62826. return this._showBoundingBox || false;
  62827. },
  62828. set: function (value) {
  62829. this._showBoundingBox = value;
  62830. // Lazyly creates a BB renderer if needed.
  62831. if (value) {
  62832. this.getScene().getBoundingBoxRenderer();
  62833. }
  62834. },
  62835. enumerable: true,
  62836. configurable: true
  62837. });
  62838. /**
  62839. * Component responsible of rendering the bounding box of the meshes in a scene.
  62840. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  62841. */
  62842. var BoundingBoxRenderer = /** @class */ (function () {
  62843. /**
  62844. * Instantiates a new bounding box renderer in a scene.
  62845. * @param scene the scene the renderer renders in
  62846. */
  62847. function BoundingBoxRenderer(scene) {
  62848. /**
  62849. * The component name helpfull to identify the component in the list of scene components.
  62850. */
  62851. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62852. /**
  62853. * Color of the bounding box lines placed in front of an object
  62854. */
  62855. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62856. /**
  62857. * Color of the bounding box lines placed behind an object
  62858. */
  62859. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62860. /**
  62861. * Defines if the renderer should show the back lines or not
  62862. */
  62863. this.showBackLines = true;
  62864. /**
  62865. * @hidden
  62866. */
  62867. this.renderList = new BABYLON.SmartArray(32);
  62868. this._vertexBuffers = {};
  62869. this.scene = scene;
  62870. scene._addComponent(this);
  62871. }
  62872. /**
  62873. * Registers the component in a given scene
  62874. */
  62875. BoundingBoxRenderer.prototype.register = function () {
  62876. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62877. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62878. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62879. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62880. };
  62881. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62882. if (mesh.showSubMeshesBoundingBox) {
  62883. var boundingInfo = subMesh.getBoundingInfo();
  62884. if (boundingInfo !== null && boundingInfo !== undefined) {
  62885. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62886. this.renderList.push(boundingInfo.boundingBox);
  62887. }
  62888. }
  62889. };
  62890. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62891. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62892. var boundingInfo = sourceMesh.getBoundingInfo();
  62893. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62894. this.renderList.push(boundingInfo.boundingBox);
  62895. }
  62896. };
  62897. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62898. if (this._colorShader) {
  62899. return;
  62900. }
  62901. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62902. attributes: [BABYLON.VertexBuffer.PositionKind],
  62903. uniforms: ["world", "viewProjection", "color"]
  62904. });
  62905. var engine = this.scene.getEngine();
  62906. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62908. this._createIndexBuffer();
  62909. };
  62910. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62911. var engine = this.scene.getEngine();
  62912. 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]);
  62913. };
  62914. /**
  62915. * Rebuilds the elements related to this component in case of
  62916. * context lost for instance.
  62917. */
  62918. BoundingBoxRenderer.prototype.rebuild = function () {
  62919. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62920. if (vb) {
  62921. vb._rebuild();
  62922. }
  62923. this._createIndexBuffer();
  62924. };
  62925. /**
  62926. * @hidden
  62927. */
  62928. BoundingBoxRenderer.prototype.reset = function () {
  62929. this.renderList.reset();
  62930. };
  62931. /**
  62932. * Render the bounding boxes of a specific rendering group
  62933. * @param renderingGroupId defines the rendering group to render
  62934. */
  62935. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62936. if (this.renderList.length === 0) {
  62937. return;
  62938. }
  62939. this._prepareRessources();
  62940. if (!this._colorShader.isReady()) {
  62941. return;
  62942. }
  62943. var engine = this.scene.getEngine();
  62944. engine.setDepthWrite(false);
  62945. this._colorShader._preBind();
  62946. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62947. var boundingBox = this.renderList.data[boundingBoxIndex];
  62948. if (boundingBox._tag !== renderingGroupId) {
  62949. continue;
  62950. }
  62951. var min = boundingBox.minimum;
  62952. var max = boundingBox.maximum;
  62953. var diff = max.subtract(min);
  62954. var median = min.add(diff.scale(0.5));
  62955. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62956. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62957. .multiply(boundingBox.getWorldMatrix());
  62958. // VBOs
  62959. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62960. if (this.showBackLines) {
  62961. // Back
  62962. engine.setDepthFunctionToGreaterOrEqual();
  62963. this.scene.resetCachedMaterial();
  62964. this._colorShader.setColor4("color", this.backColor.toColor4());
  62965. this._colorShader.bind(worldMatrix);
  62966. // Draw order
  62967. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62968. }
  62969. // Front
  62970. engine.setDepthFunctionToLess();
  62971. this.scene.resetCachedMaterial();
  62972. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62973. this._colorShader.bind(worldMatrix);
  62974. // Draw order
  62975. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62976. }
  62977. this._colorShader.unbind();
  62978. engine.setDepthFunctionToLessOrEqual();
  62979. engine.setDepthWrite(true);
  62980. };
  62981. /**
  62982. * In case of occlusion queries, we can render the occlusion bounding box through this method
  62983. * @param mesh Define the mesh to render the occlusion bounding box for
  62984. */
  62985. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62986. this._prepareRessources();
  62987. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  62988. return;
  62989. }
  62990. var engine = this.scene.getEngine();
  62991. engine.setDepthWrite(false);
  62992. engine.setColorWrite(false);
  62993. this._colorShader._preBind();
  62994. var boundingBox = mesh._boundingInfo.boundingBox;
  62995. var min = boundingBox.minimum;
  62996. var max = boundingBox.maximum;
  62997. var diff = max.subtract(min);
  62998. var median = min.add(diff.scale(0.5));
  62999. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63000. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63001. .multiply(boundingBox.getWorldMatrix());
  63002. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63003. engine.setDepthFunctionToLess();
  63004. this.scene.resetCachedMaterial();
  63005. this._colorShader.bind(worldMatrix);
  63006. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63007. this._colorShader.unbind();
  63008. engine.setDepthFunctionToLessOrEqual();
  63009. engine.setDepthWrite(true);
  63010. engine.setColorWrite(true);
  63011. };
  63012. /**
  63013. * Dispose and release the resources attached to this renderer.
  63014. */
  63015. BoundingBoxRenderer.prototype.dispose = function () {
  63016. if (!this._colorShader) {
  63017. return;
  63018. }
  63019. this.renderList.dispose();
  63020. this._colorShader.dispose();
  63021. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63022. if (buffer) {
  63023. buffer.dispose();
  63024. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63025. }
  63026. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63027. };
  63028. return BoundingBoxRenderer;
  63029. }());
  63030. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63031. })(BABYLON || (BABYLON = {}));
  63032. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63033. var BABYLON;
  63034. (function (BABYLON) {
  63035. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63036. return this._gl.createTransformFeedback();
  63037. };
  63038. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63039. this._gl.deleteTransformFeedback(value);
  63040. };
  63041. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63042. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63043. };
  63044. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63045. if (usePoints === void 0) { usePoints = true; }
  63046. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63047. };
  63048. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63049. this._gl.endTransformFeedback();
  63050. };
  63051. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63052. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63053. };
  63054. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63055. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63056. };
  63057. })(BABYLON || (BABYLON = {}));
  63058. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63059. var BABYLON;
  63060. (function (BABYLON) {
  63061. /**
  63062. * This represents a GPU particle system in Babylon
  63063. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63064. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63065. */
  63066. var GPUParticleSystem = /** @class */ (function (_super) {
  63067. __extends(GPUParticleSystem, _super);
  63068. /**
  63069. * Instantiates a GPU particle system.
  63070. * 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.
  63071. * @param name The name of the particle system
  63072. * @param options The options used to create the system
  63073. * @param scene The scene the particle system belongs to
  63074. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63075. */
  63076. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63077. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63078. var _this = _super.call(this, name) || this;
  63079. /**
  63080. * The layer mask we are rendering the particles through.
  63081. */
  63082. _this.layerMask = 0x0FFFFFFF;
  63083. _this._accumulatedCount = 0;
  63084. _this._targetIndex = 0;
  63085. _this._currentRenderId = -1;
  63086. _this._started = false;
  63087. _this._stopped = false;
  63088. _this._timeDelta = 0;
  63089. _this._attributesStrideSize = 21;
  63090. _this._actualFrame = 0;
  63091. _this._rawTextureWidth = 256;
  63092. /**
  63093. * An event triggered when the system is disposed.
  63094. */
  63095. _this.onDisposeObservable = new BABYLON.Observable();
  63096. /**
  63097. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  63098. * to override the particles.
  63099. */
  63100. _this.forceDepthWrite = false;
  63101. _this._preWarmDone = false;
  63102. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63103. // Setup the default processing configuration to the scene.
  63104. _this._attachImageProcessingConfiguration(null);
  63105. _this._engine = _this._scene.getEngine();
  63106. if (!options.randomTextureSize) {
  63107. delete options.randomTextureSize;
  63108. }
  63109. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  63110. var optionsAsNumber = options;
  63111. if (isFinite(optionsAsNumber)) {
  63112. fullOptions.capacity = optionsAsNumber;
  63113. }
  63114. _this._capacity = fullOptions.capacity;
  63115. _this._activeCount = fullOptions.capacity;
  63116. _this._currentActiveCount = 0;
  63117. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  63118. _this._scene.particleSystems.push(_this);
  63119. _this._updateEffectOptions = {
  63120. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  63121. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  63122. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  63123. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  63124. uniformBuffersNames: [],
  63125. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  63126. defines: "",
  63127. fallbacks: null,
  63128. onCompiled: null,
  63129. onError: null,
  63130. indexParameters: null,
  63131. maxSimultaneousLights: 0,
  63132. transformFeedbackVaryings: []
  63133. };
  63134. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  63135. // Random data
  63136. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  63137. var d = [];
  63138. for (var i = 0; i < maxTextureSize; ++i) {
  63139. d.push(Math.random());
  63140. d.push(Math.random());
  63141. d.push(Math.random());
  63142. d.push(Math.random());
  63143. }
  63144. _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);
  63145. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63146. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63147. d = [];
  63148. for (var i = 0; i < maxTextureSize; ++i) {
  63149. d.push(Math.random());
  63150. d.push(Math.random());
  63151. d.push(Math.random());
  63152. d.push(Math.random());
  63153. }
  63154. _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);
  63155. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63156. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63157. _this._randomTextureSize = maxTextureSize;
  63158. return _this;
  63159. }
  63160. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  63161. /**
  63162. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  63163. */
  63164. get: function () {
  63165. if (!BABYLON.Engine.LastCreatedEngine) {
  63166. return false;
  63167. }
  63168. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  63169. },
  63170. enumerable: true,
  63171. configurable: true
  63172. });
  63173. /**
  63174. * Gets the maximum number of particles active at the same time.
  63175. * @returns The max number of active particles.
  63176. */
  63177. GPUParticleSystem.prototype.getCapacity = function () {
  63178. return this._capacity;
  63179. };
  63180. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  63181. /**
  63182. * Gets or set the number of active particles
  63183. */
  63184. get: function () {
  63185. return this._activeCount;
  63186. },
  63187. set: function (value) {
  63188. this._activeCount = Math.min(value, this._capacity);
  63189. },
  63190. enumerable: true,
  63191. configurable: true
  63192. });
  63193. /**
  63194. * Is this system ready to be used/rendered
  63195. * @return true if the system is ready
  63196. */
  63197. GPUParticleSystem.prototype.isReady = function () {
  63198. if (!this._updateEffect) {
  63199. this._recreateUpdateEffect();
  63200. this._recreateRenderEffect();
  63201. return false;
  63202. }
  63203. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  63204. return false;
  63205. }
  63206. return true;
  63207. };
  63208. /**
  63209. * Gets if the system has been started. (Note: this will still be true after stop is called)
  63210. * @returns True if it has been started, otherwise false.
  63211. */
  63212. GPUParticleSystem.prototype.isStarted = function () {
  63213. return this._started;
  63214. };
  63215. /**
  63216. * Starts the particle system and begins to emit
  63217. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  63218. */
  63219. GPUParticleSystem.prototype.start = function (delay) {
  63220. var _this = this;
  63221. if (delay === void 0) { delay = this.startDelay; }
  63222. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  63223. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  63224. }
  63225. if (delay) {
  63226. setTimeout(function () {
  63227. _this.start(0);
  63228. }, delay);
  63229. return;
  63230. }
  63231. this._started = true;
  63232. this._stopped = false;
  63233. this._preWarmDone = false;
  63234. // Animations
  63235. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  63236. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  63237. }
  63238. };
  63239. /**
  63240. * Stops the particle system.
  63241. */
  63242. GPUParticleSystem.prototype.stop = function () {
  63243. this._stopped = true;
  63244. };
  63245. /**
  63246. * Remove all active particles
  63247. */
  63248. GPUParticleSystem.prototype.reset = function () {
  63249. this._releaseBuffers();
  63250. this._releaseVAOs();
  63251. this._currentActiveCount = 0;
  63252. this._targetIndex = 0;
  63253. };
  63254. /**
  63255. * Returns the string "GPUParticleSystem"
  63256. * @returns a string containing the class name
  63257. */
  63258. GPUParticleSystem.prototype.getClassName = function () {
  63259. return "GPUParticleSystem";
  63260. };
  63261. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63262. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63263. this._releaseBuffers();
  63264. return this;
  63265. };
  63266. /**
  63267. * Adds a new color gradient
  63268. * @param gradient defines the gradient to use (between 0 and 1)
  63269. * @param color1 defines the color to affect to the specified gradient
  63270. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63271. * @returns the current particle system
  63272. */
  63273. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63274. if (!this._colorGradients) {
  63275. this._colorGradients = [];
  63276. }
  63277. var colorGradient = new BABYLON.ColorGradient();
  63278. colorGradient.gradient = gradient;
  63279. colorGradient.color1 = color1;
  63280. this._colorGradients.push(colorGradient);
  63281. this._colorGradients.sort(function (a, b) {
  63282. if (a.gradient < b.gradient) {
  63283. return -1;
  63284. }
  63285. else if (a.gradient > b.gradient) {
  63286. return 1;
  63287. }
  63288. return 0;
  63289. });
  63290. if (this._colorGradientsTexture) {
  63291. this._colorGradientsTexture.dispose();
  63292. this._colorGradientsTexture = null;
  63293. }
  63294. this._releaseBuffers();
  63295. return this;
  63296. };
  63297. /**
  63298. * Remove a specific color gradient
  63299. * @param gradient defines the gradient to remove
  63300. * @returns the current particle system
  63301. */
  63302. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63303. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63304. this._colorGradientsTexture = null;
  63305. return this;
  63306. };
  63307. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63308. var valueGradient = new BABYLON.FactorGradient();
  63309. valueGradient.gradient = gradient;
  63310. valueGradient.factor1 = factor;
  63311. factorGradients.push(valueGradient);
  63312. factorGradients.sort(function (a, b) {
  63313. if (a.gradient < b.gradient) {
  63314. return -1;
  63315. }
  63316. else if (a.gradient > b.gradient) {
  63317. return 1;
  63318. }
  63319. return 0;
  63320. });
  63321. this._releaseBuffers();
  63322. };
  63323. /**
  63324. * Adds a new size gradient
  63325. * @param gradient defines the gradient to use (between 0 and 1)
  63326. * @param factor defines the size factor to affect to the specified gradient
  63327. * @returns the current particle system
  63328. */
  63329. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63330. if (!this._sizeGradients) {
  63331. this._sizeGradients = [];
  63332. }
  63333. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63334. if (this._sizeGradientsTexture) {
  63335. this._sizeGradientsTexture.dispose();
  63336. this._sizeGradientsTexture = null;
  63337. }
  63338. this._releaseBuffers();
  63339. return this;
  63340. };
  63341. /**
  63342. * Remove a specific size gradient
  63343. * @param gradient defines the gradient to remove
  63344. * @returns the current particle system
  63345. */
  63346. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63347. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63348. this._sizeGradientsTexture = null;
  63349. return this;
  63350. };
  63351. /**
  63352. * Adds a new angular speed gradient
  63353. * @param gradient defines the gradient to use (between 0 and 1)
  63354. * @param factor defines the angular speed to affect to the specified gradient
  63355. * @returns the current particle system
  63356. */
  63357. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63358. if (!this._angularSpeedGradients) {
  63359. this._angularSpeedGradients = [];
  63360. }
  63361. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63362. if (this._angularSpeedGradientsTexture) {
  63363. this._angularSpeedGradientsTexture.dispose();
  63364. this._angularSpeedGradientsTexture = null;
  63365. }
  63366. this._releaseBuffers();
  63367. return this;
  63368. };
  63369. /**
  63370. * Remove a specific angular speed gradient
  63371. * @param gradient defines the gradient to remove
  63372. * @returns the current particle system
  63373. */
  63374. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63375. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63376. this._angularSpeedGradientsTexture = null;
  63377. return this;
  63378. };
  63379. /**
  63380. * Adds a new velocity gradient
  63381. * @param gradient defines the gradient to use (between 0 and 1)
  63382. * @param factor defines the velocity to affect to the specified gradient
  63383. * @returns the current particle system
  63384. */
  63385. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63386. if (!this._velocityGradients) {
  63387. this._velocityGradients = [];
  63388. }
  63389. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63390. if (this._velocityGradientsTexture) {
  63391. this._velocityGradientsTexture.dispose();
  63392. this._velocityGradientsTexture = null;
  63393. }
  63394. this._releaseBuffers();
  63395. return this;
  63396. };
  63397. /**
  63398. * Remove a specific velocity gradient
  63399. * @param gradient defines the gradient to remove
  63400. * @returns the current particle system
  63401. */
  63402. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63403. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63404. this._velocityGradientsTexture = null;
  63405. return this;
  63406. };
  63407. /**
  63408. * Adds a new limit velocity gradient
  63409. * @param gradient defines the gradient to use (between 0 and 1)
  63410. * @param factor defines the limit velocity value to affect to the specified gradient
  63411. * @returns the current particle system
  63412. */
  63413. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63414. if (!this._limitVelocityGradients) {
  63415. this._limitVelocityGradients = [];
  63416. }
  63417. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63418. if (this._limitVelocityGradientsTexture) {
  63419. this._limitVelocityGradientsTexture.dispose();
  63420. this._limitVelocityGradientsTexture = null;
  63421. }
  63422. this._releaseBuffers();
  63423. return this;
  63424. };
  63425. /**
  63426. * Remove a specific limit velocity gradient
  63427. * @param gradient defines the gradient to remove
  63428. * @returns the current particle system
  63429. */
  63430. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63431. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63432. this._limitVelocityGradientsTexture = null;
  63433. return this;
  63434. };
  63435. /**
  63436. * Adds a new drag gradient
  63437. * @param gradient defines the gradient to use (between 0 and 1)
  63438. * @param factor defines the drag value to affect to the specified gradient
  63439. * @returns the current particle system
  63440. */
  63441. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63442. if (!this._dragGradients) {
  63443. this._dragGradients = [];
  63444. }
  63445. this._addFactorGradient(this._dragGradients, gradient, factor);
  63446. if (this._dragGradientsTexture) {
  63447. this._dragGradientsTexture.dispose();
  63448. this._dragGradientsTexture = null;
  63449. }
  63450. this._releaseBuffers();
  63451. return this;
  63452. };
  63453. /**
  63454. * Remove a specific drag gradient
  63455. * @param gradient defines the gradient to remove
  63456. * @returns the current particle system
  63457. */
  63458. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63459. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63460. this._dragGradientsTexture = null;
  63461. return this;
  63462. };
  63463. /**
  63464. * Not supported by GPUParticleSystem
  63465. * @param gradient defines the gradient to use (between 0 and 1)
  63466. * @param factor defines the emit rate value to affect to the specified gradient
  63467. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63468. * @returns the current particle system
  63469. */
  63470. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63471. // Do nothing as emit rate is not supported by GPUParticleSystem
  63472. return this;
  63473. };
  63474. /**
  63475. * Not supported by GPUParticleSystem
  63476. * @param gradient defines the gradient to remove
  63477. * @returns the current particle system
  63478. */
  63479. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63480. // Do nothing as emit rate is not supported by GPUParticleSystem
  63481. return this;
  63482. };
  63483. /**
  63484. * Not supported by GPUParticleSystem
  63485. * @param gradient defines the gradient to use (between 0 and 1)
  63486. * @param factor defines the start size value to affect to the specified gradient
  63487. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63488. * @returns the current particle system
  63489. */
  63490. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63491. // Do nothing as start size is not supported by GPUParticleSystem
  63492. return this;
  63493. };
  63494. /**
  63495. * Not supported by GPUParticleSystem
  63496. * @param gradient defines the gradient to remove
  63497. * @returns the current particle system
  63498. */
  63499. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63500. // Do nothing as start size is not supported by GPUParticleSystem
  63501. return this;
  63502. };
  63503. /**
  63504. * Not supported by GPUParticleSystem
  63505. * @param gradient defines the gradient to use (between 0 and 1)
  63506. * @param min defines the color remap minimal range
  63507. * @param max defines the color remap maximal range
  63508. * @returns the current particle system
  63509. */
  63510. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63511. // Do nothing as start size is not supported by GPUParticleSystem
  63512. return this;
  63513. };
  63514. /**
  63515. * Not supported by GPUParticleSystem
  63516. * @param gradient defines the gradient to remove
  63517. * @returns the current particle system
  63518. */
  63519. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63520. // Do nothing as start size is not supported by GPUParticleSystem
  63521. return this;
  63522. };
  63523. /**
  63524. * Not supported by GPUParticleSystem
  63525. * @param gradient defines the gradient to use (between 0 and 1)
  63526. * @param min defines the alpha remap minimal range
  63527. * @param max defines the alpha remap maximal range
  63528. * @returns the current particle system
  63529. */
  63530. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63531. // Do nothing as start size is not supported by GPUParticleSystem
  63532. return this;
  63533. };
  63534. /**
  63535. * Not supported by GPUParticleSystem
  63536. * @param gradient defines the gradient to remove
  63537. * @returns the current particle system
  63538. */
  63539. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63540. // Do nothing as start size is not supported by GPUParticleSystem
  63541. return this;
  63542. };
  63543. /**
  63544. * Not supported by GPUParticleSystem
  63545. * @param gradient defines the gradient to use (between 0 and 1)
  63546. * @param color defines the color to affect to the specified gradient
  63547. * @returns the current particle system
  63548. */
  63549. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63550. //Not supported by GPUParticleSystem
  63551. return this;
  63552. };
  63553. /**
  63554. * Not supported by GPUParticleSystem
  63555. * @param gradient defines the gradient to remove
  63556. * @returns the current particle system
  63557. */
  63558. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63559. //Not supported by GPUParticleSystem
  63560. return this;
  63561. };
  63562. /**
  63563. * Not supported by GPUParticleSystem
  63564. * @returns the list of ramp gradients
  63565. */
  63566. GPUParticleSystem.prototype.getRampGradients = function () {
  63567. return null;
  63568. };
  63569. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63570. /**
  63571. * Not supported by GPUParticleSystem
  63572. * Gets or sets a boolean indicating that ramp gradients must be used
  63573. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63574. */
  63575. get: function () {
  63576. //Not supported by GPUParticleSystem
  63577. return false;
  63578. },
  63579. set: function (value) {
  63580. //Not supported by GPUParticleSystem
  63581. },
  63582. enumerable: true,
  63583. configurable: true
  63584. });
  63585. /**
  63586. * Not supported by GPUParticleSystem
  63587. * @param gradient defines the gradient to use (between 0 and 1)
  63588. * @param factor defines the life time factor to affect to the specified gradient
  63589. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63590. * @returns the current particle system
  63591. */
  63592. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  63593. //Not supported by GPUParticleSystem
  63594. return this;
  63595. };
  63596. /**
  63597. * Not supported by GPUParticleSystem
  63598. * @param gradient defines the gradient to remove
  63599. * @returns the current particle system
  63600. */
  63601. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  63602. //Not supported by GPUParticleSystem
  63603. return this;
  63604. };
  63605. GPUParticleSystem.prototype._reset = function () {
  63606. this._releaseBuffers();
  63607. };
  63608. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63609. var updateVertexBuffers = {};
  63610. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63611. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63612. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63613. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63614. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63615. var offset = 12;
  63616. if (!this._colorGradientsTexture) {
  63617. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63618. offset += 4;
  63619. }
  63620. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63621. offset += 3;
  63622. if (!this._isBillboardBased) {
  63623. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63624. offset += 3;
  63625. }
  63626. if (this._angularSpeedGradientsTexture) {
  63627. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63628. offset += 1;
  63629. }
  63630. else {
  63631. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63632. offset += 2;
  63633. }
  63634. if (this._isAnimationSheetEnabled) {
  63635. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63636. offset += 1;
  63637. if (this.spriteRandomStartCell) {
  63638. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63639. offset += 1;
  63640. }
  63641. }
  63642. if (this.noiseTexture) {
  63643. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63644. offset += 3;
  63645. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63646. offset += 3;
  63647. }
  63648. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63649. this._engine.bindArrayBuffer(null);
  63650. return vao;
  63651. };
  63652. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63653. var renderVertexBuffers = {};
  63654. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63655. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63656. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63657. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63658. var offset = 12;
  63659. if (!this._colorGradientsTexture) {
  63660. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63661. offset += 4;
  63662. }
  63663. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63664. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63665. }
  63666. offset += 3; // Direction
  63667. if (!this._isBillboardBased) {
  63668. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63669. offset += 3;
  63670. }
  63671. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63672. if (this._angularSpeedGradientsTexture) {
  63673. offset++;
  63674. }
  63675. else {
  63676. offset += 2;
  63677. }
  63678. if (this._isAnimationSheetEnabled) {
  63679. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63680. offset += 1;
  63681. if (this.spriteRandomStartCell) {
  63682. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63683. offset += 1;
  63684. }
  63685. }
  63686. if (this.noiseTexture) {
  63687. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63688. offset += 3;
  63689. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63690. offset += 3;
  63691. }
  63692. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63693. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63694. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63695. this._engine.bindArrayBuffer(null);
  63696. return vao;
  63697. };
  63698. GPUParticleSystem.prototype._initialize = function (force) {
  63699. if (force === void 0) { force = false; }
  63700. if (this._buffer0 && !force) {
  63701. return;
  63702. }
  63703. var engine = this._scene.getEngine();
  63704. var data = new Array();
  63705. if (!this.isBillboardBased) {
  63706. this._attributesStrideSize += 3;
  63707. }
  63708. if (this._colorGradientsTexture) {
  63709. this._attributesStrideSize -= 4;
  63710. }
  63711. if (this._angularSpeedGradientsTexture) {
  63712. this._attributesStrideSize -= 1;
  63713. }
  63714. if (this._isAnimationSheetEnabled) {
  63715. this._attributesStrideSize += 1;
  63716. if (this.spriteRandomStartCell) {
  63717. this._attributesStrideSize += 1;
  63718. }
  63719. }
  63720. if (this.noiseTexture) {
  63721. this._attributesStrideSize += 6;
  63722. }
  63723. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63724. // position
  63725. data.push(0.0);
  63726. data.push(0.0);
  63727. data.push(0.0);
  63728. // Age and life
  63729. data.push(0.0); // create the particle as a dead one to create a new one at start
  63730. data.push(0.0);
  63731. // Seed
  63732. data.push(Math.random());
  63733. data.push(Math.random());
  63734. data.push(Math.random());
  63735. data.push(Math.random());
  63736. // Size
  63737. data.push(0.0);
  63738. data.push(0.0);
  63739. data.push(0.0);
  63740. if (!this._colorGradientsTexture) {
  63741. // color
  63742. data.push(0.0);
  63743. data.push(0.0);
  63744. data.push(0.0);
  63745. data.push(0.0);
  63746. }
  63747. // direction
  63748. data.push(0.0);
  63749. data.push(0.0);
  63750. data.push(0.0);
  63751. if (!this.isBillboardBased) {
  63752. // initialDirection
  63753. data.push(0.0);
  63754. data.push(0.0);
  63755. data.push(0.0);
  63756. }
  63757. // angle
  63758. data.push(0.0);
  63759. if (!this._angularSpeedGradientsTexture) {
  63760. data.push(0.0);
  63761. }
  63762. if (this._isAnimationSheetEnabled) {
  63763. data.push(0.0);
  63764. if (this.spriteRandomStartCell) {
  63765. data.push(0.0);
  63766. }
  63767. }
  63768. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  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. data.push(Math.random());
  63775. }
  63776. }
  63777. // Sprite data
  63778. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63779. -0.5, 0.5, 0, 1,
  63780. -0.5, -0.5, 0, 0,
  63781. 0.5, -0.5, 1, 0]);
  63782. // Buffers
  63783. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63784. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63785. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63786. // Update VAO
  63787. this._updateVAO = [];
  63788. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63789. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63790. // Render VAO
  63791. this._renderVAO = [];
  63792. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63793. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63794. // Links
  63795. this._sourceBuffer = this._buffer0;
  63796. this._targetBuffer = this._buffer1;
  63797. };
  63798. /** @hidden */
  63799. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63800. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63801. if (this._isBillboardBased) {
  63802. defines += "\n#define BILLBOARD";
  63803. }
  63804. if (this._colorGradientsTexture) {
  63805. defines += "\n#define COLORGRADIENTS";
  63806. }
  63807. if (this._sizeGradientsTexture) {
  63808. defines += "\n#define SIZEGRADIENTS";
  63809. }
  63810. if (this._angularSpeedGradientsTexture) {
  63811. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63812. }
  63813. if (this._velocityGradientsTexture) {
  63814. defines += "\n#define VELOCITYGRADIENTS";
  63815. }
  63816. if (this._limitVelocityGradientsTexture) {
  63817. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63818. }
  63819. if (this._dragGradientsTexture) {
  63820. defines += "\n#define DRAGGRADIENTS";
  63821. }
  63822. if (this.isAnimationSheetEnabled) {
  63823. defines += "\n#define ANIMATESHEET";
  63824. if (this.spriteRandomStartCell) {
  63825. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63826. }
  63827. }
  63828. if (this.noiseTexture) {
  63829. defines += "\n#define NOISE";
  63830. }
  63831. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63832. return;
  63833. }
  63834. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63835. if (!this._colorGradientsTexture) {
  63836. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63837. }
  63838. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63839. if (!this._isBillboardBased) {
  63840. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63841. }
  63842. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63843. if (this.isAnimationSheetEnabled) {
  63844. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63845. if (this.spriteRandomStartCell) {
  63846. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63847. }
  63848. }
  63849. if (this.noiseTexture) {
  63850. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63851. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63852. }
  63853. this._updateEffectOptions.defines = defines;
  63854. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63855. };
  63856. /** @hidden */
  63857. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63858. var defines = "";
  63859. if (this._scene.clipPlane) {
  63860. defines = "\n#define CLIPPLANE";
  63861. }
  63862. if (this._scene.clipPlane2) {
  63863. defines = "\n#define CLIPPLANE2";
  63864. }
  63865. if (this._scene.clipPlane3) {
  63866. defines = "\n#define CLIPPLANE3";
  63867. }
  63868. if (this._scene.clipPlane4) {
  63869. defines = "\n#define CLIPPLANE4";
  63870. }
  63871. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63872. defines = "\n#define BLENDMULTIPLYMODE";
  63873. }
  63874. if (this._isBillboardBased) {
  63875. defines += "\n#define BILLBOARD";
  63876. switch (this.billboardMode) {
  63877. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63878. defines += "\n#define BILLBOARDY";
  63879. break;
  63880. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63881. defines += "\n#define BILLBOARDSTRETCHED";
  63882. break;
  63883. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63884. default:
  63885. break;
  63886. }
  63887. }
  63888. if (this._colorGradientsTexture) {
  63889. defines += "\n#define COLORGRADIENTS";
  63890. }
  63891. if (this.isAnimationSheetEnabled) {
  63892. defines += "\n#define ANIMATESHEET";
  63893. }
  63894. if (this._imageProcessingConfiguration) {
  63895. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63896. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63897. }
  63898. if (this._renderEffect && this._renderEffect.defines === defines) {
  63899. return;
  63900. }
  63901. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63902. var samplers = ["textureSampler", "colorGradientSampler"];
  63903. if (BABYLON.ImageProcessingConfiguration) {
  63904. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63905. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63906. }
  63907. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63908. };
  63909. /**
  63910. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63911. * @param preWarm defines if we are in the pre-warmimg phase
  63912. */
  63913. GPUParticleSystem.prototype.animate = function (preWarm) {
  63914. if (preWarm === void 0) { preWarm = false; }
  63915. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63916. this._actualFrame += this._timeDelta;
  63917. if (!this._stopped) {
  63918. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63919. this.stop();
  63920. }
  63921. }
  63922. };
  63923. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63924. var texture = this[textureName];
  63925. if (!factorGradients || !factorGradients.length || texture) {
  63926. return;
  63927. }
  63928. var data = new Float32Array(this._rawTextureWidth);
  63929. for (var x = 0; x < this._rawTextureWidth; x++) {
  63930. var ratio = x / this._rawTextureWidth;
  63931. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63932. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63933. });
  63934. }
  63935. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63936. };
  63937. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63938. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63939. };
  63940. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63941. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63942. };
  63943. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63944. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63945. };
  63946. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63947. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63948. };
  63949. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63950. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63951. };
  63952. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63953. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63954. return;
  63955. }
  63956. var data = new Uint8Array(this._rawTextureWidth * 4);
  63957. var tmpColor = BABYLON.Tmp.Color4[0];
  63958. for (var x = 0; x < this._rawTextureWidth; x++) {
  63959. var ratio = x / this._rawTextureWidth;
  63960. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63961. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63962. data[x * 4] = tmpColor.r * 255;
  63963. data[x * 4 + 1] = tmpColor.g * 255;
  63964. data[x * 4 + 2] = tmpColor.b * 255;
  63965. data[x * 4 + 3] = tmpColor.a * 255;
  63966. });
  63967. }
  63968. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63969. };
  63970. /**
  63971. * Renders the particle system in its current state
  63972. * @param preWarm defines if the system should only update the particles but not render them
  63973. * @returns the current number of particles
  63974. */
  63975. GPUParticleSystem.prototype.render = function (preWarm) {
  63976. if (preWarm === void 0) { preWarm = false; }
  63977. if (!this._started) {
  63978. return 0;
  63979. }
  63980. this._createColorGradientTexture();
  63981. this._createSizeGradientTexture();
  63982. this._createAngularSpeedGradientTexture();
  63983. this._createVelocityGradientTexture();
  63984. this._createLimitVelocityGradientTexture();
  63985. this._createDragGradientTexture();
  63986. this._recreateUpdateEffect();
  63987. this._recreateRenderEffect();
  63988. if (!this.isReady()) {
  63989. return 0;
  63990. }
  63991. if (!preWarm) {
  63992. if (!this._preWarmDone && this.preWarmCycles) {
  63993. for (var index = 0; index < this.preWarmCycles; index++) {
  63994. this.animate(true);
  63995. this.render(true);
  63996. }
  63997. this._preWarmDone = true;
  63998. }
  63999. if (this._currentRenderId === this._scene.getRenderId()) {
  64000. return 0;
  64001. }
  64002. this._currentRenderId = this._scene.getRenderId();
  64003. }
  64004. // Get everything ready to render
  64005. this._initialize();
  64006. this._accumulatedCount += this.emitRate * this._timeDelta;
  64007. if (this._accumulatedCount > 1) {
  64008. var intPart = this._accumulatedCount | 0;
  64009. this._accumulatedCount -= intPart;
  64010. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64011. }
  64012. if (!this._currentActiveCount) {
  64013. return 0;
  64014. }
  64015. // Enable update effect
  64016. this._engine.enableEffect(this._updateEffect);
  64017. this._engine.setState(false);
  64018. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64019. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64020. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64021. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64022. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64023. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64024. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64025. if (!this._colorGradientsTexture) {
  64026. this._updateEffect.setDirectColor4("color1", this.color1);
  64027. this._updateEffect.setDirectColor4("color2", this.color2);
  64028. }
  64029. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64030. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64031. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64032. this._updateEffect.setVector3("gravity", this.gravity);
  64033. if (this._sizeGradientsTexture) {
  64034. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64035. }
  64036. if (this._angularSpeedGradientsTexture) {
  64037. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64038. }
  64039. if (this._velocityGradientsTexture) {
  64040. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64041. }
  64042. if (this._limitVelocityGradientsTexture) {
  64043. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64044. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64045. }
  64046. if (this._dragGradientsTexture) {
  64047. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64048. }
  64049. if (this.particleEmitterType) {
  64050. this.particleEmitterType.applyToShader(this._updateEffect);
  64051. }
  64052. if (this._isAnimationSheetEnabled) {
  64053. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64054. }
  64055. if (this.noiseTexture) {
  64056. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64057. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64058. }
  64059. var emitterWM;
  64060. if (this.emitter.position) {
  64061. var emitterMesh = this.emitter;
  64062. emitterWM = emitterMesh.getWorldMatrix();
  64063. }
  64064. else {
  64065. var emitterPosition = this.emitter;
  64066. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64067. }
  64068. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64069. // Bind source VAO
  64070. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64071. // Update
  64072. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64073. this._engine.setRasterizerState(false);
  64074. this._engine.beginTransformFeedback(true);
  64075. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64076. this._engine.endTransformFeedback();
  64077. this._engine.setRasterizerState(true);
  64078. this._engine.bindTransformFeedbackBuffer(null);
  64079. if (!preWarm) {
  64080. // Enable render effect
  64081. this._engine.enableEffect(this._renderEffect);
  64082. var viewMatrix = this._scene.getViewMatrix();
  64083. this._renderEffect.setMatrix("view", viewMatrix);
  64084. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  64085. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  64086. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  64087. if (this._colorGradientsTexture) {
  64088. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  64089. }
  64090. else {
  64091. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  64092. }
  64093. if (this._isAnimationSheetEnabled && this.particleTexture) {
  64094. var baseSize = this.particleTexture.getBaseSize();
  64095. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  64096. }
  64097. if (this._isBillboardBased) {
  64098. var camera = this._scene.activeCamera;
  64099. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  64100. }
  64101. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  64102. var invView = viewMatrix.clone();
  64103. invView.invert();
  64104. this._renderEffect.setMatrix("invView", invView);
  64105. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  64106. }
  64107. // image processing
  64108. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  64109. this._imageProcessingConfiguration.bind(this._renderEffect);
  64110. }
  64111. // Draw order
  64112. switch (this.blendMode) {
  64113. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  64114. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  64115. break;
  64116. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  64117. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  64118. break;
  64119. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  64120. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64121. break;
  64122. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  64123. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  64124. break;
  64125. }
  64126. if (this.forceDepthWrite) {
  64127. this._engine.setDepthWrite(true);
  64128. }
  64129. // Bind source VAO
  64130. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  64131. // Render
  64132. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  64133. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64134. }
  64135. // Switch VAOs
  64136. this._targetIndex++;
  64137. if (this._targetIndex === 2) {
  64138. this._targetIndex = 0;
  64139. }
  64140. // Switch buffers
  64141. var tmpBuffer = this._sourceBuffer;
  64142. this._sourceBuffer = this._targetBuffer;
  64143. this._targetBuffer = tmpBuffer;
  64144. return this._currentActiveCount;
  64145. };
  64146. /**
  64147. * Rebuilds the particle system
  64148. */
  64149. GPUParticleSystem.prototype.rebuild = function () {
  64150. this._initialize(true);
  64151. };
  64152. GPUParticleSystem.prototype._releaseBuffers = function () {
  64153. if (this._buffer0) {
  64154. this._buffer0.dispose();
  64155. this._buffer0 = null;
  64156. }
  64157. if (this._buffer1) {
  64158. this._buffer1.dispose();
  64159. this._buffer1 = null;
  64160. }
  64161. if (this._spriteBuffer) {
  64162. this._spriteBuffer.dispose();
  64163. this._spriteBuffer = null;
  64164. }
  64165. };
  64166. GPUParticleSystem.prototype._releaseVAOs = function () {
  64167. if (!this._updateVAO) {
  64168. return;
  64169. }
  64170. for (var index = 0; index < this._updateVAO.length; index++) {
  64171. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  64172. }
  64173. this._updateVAO = [];
  64174. for (var index = 0; index < this._renderVAO.length; index++) {
  64175. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  64176. }
  64177. this._renderVAO = [];
  64178. };
  64179. /**
  64180. * Disposes the particle system and free the associated resources
  64181. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  64182. */
  64183. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  64184. if (disposeTexture === void 0) { disposeTexture = true; }
  64185. var index = this._scene.particleSystems.indexOf(this);
  64186. if (index > -1) {
  64187. this._scene.particleSystems.splice(index, 1);
  64188. }
  64189. this._releaseBuffers();
  64190. this._releaseVAOs();
  64191. if (this._colorGradientsTexture) {
  64192. this._colorGradientsTexture.dispose();
  64193. this._colorGradientsTexture = null;
  64194. }
  64195. if (this._sizeGradientsTexture) {
  64196. this._sizeGradientsTexture.dispose();
  64197. this._sizeGradientsTexture = null;
  64198. }
  64199. if (this._angularSpeedGradientsTexture) {
  64200. this._angularSpeedGradientsTexture.dispose();
  64201. this._angularSpeedGradientsTexture = null;
  64202. }
  64203. if (this._velocityGradientsTexture) {
  64204. this._velocityGradientsTexture.dispose();
  64205. this._velocityGradientsTexture = null;
  64206. }
  64207. if (this._limitVelocityGradientsTexture) {
  64208. this._limitVelocityGradientsTexture.dispose();
  64209. this._limitVelocityGradientsTexture = null;
  64210. }
  64211. if (this._dragGradientsTexture) {
  64212. this._dragGradientsTexture.dispose();
  64213. this._dragGradientsTexture = null;
  64214. }
  64215. if (this._randomTexture) {
  64216. this._randomTexture.dispose();
  64217. this._randomTexture = null;
  64218. }
  64219. if (this._randomTexture2) {
  64220. this._randomTexture2.dispose();
  64221. this._randomTexture2 = null;
  64222. }
  64223. if (disposeTexture && this.particleTexture) {
  64224. this.particleTexture.dispose();
  64225. this.particleTexture = null;
  64226. }
  64227. if (disposeTexture && this.noiseTexture) {
  64228. this.noiseTexture.dispose();
  64229. this.noiseTexture = null;
  64230. }
  64231. // Callback
  64232. this.onDisposeObservable.notifyObservers(this);
  64233. this.onDisposeObservable.clear();
  64234. };
  64235. /**
  64236. * Clones the particle system.
  64237. * @param name The name of the cloned object
  64238. * @param newEmitter The new emitter to use
  64239. * @returns the cloned particle system
  64240. */
  64241. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  64242. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  64243. BABYLON.Tools.DeepCopy(this, result);
  64244. if (newEmitter === undefined) {
  64245. newEmitter = this.emitter;
  64246. }
  64247. result.emitter = newEmitter;
  64248. if (this.particleTexture) {
  64249. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  64250. }
  64251. return result;
  64252. };
  64253. /**
  64254. * Serializes the particle system to a JSON object.
  64255. * @returns the JSON object
  64256. */
  64257. GPUParticleSystem.prototype.serialize = function () {
  64258. var serializationObject = {};
  64259. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  64260. serializationObject.activeParticleCount = this.activeParticleCount;
  64261. return serializationObject;
  64262. };
  64263. /**
  64264. * Parses a JSON object to create a GPU particle system.
  64265. * @param parsedParticleSystem The JSON object to parse
  64266. * @param scene The scene to create the particle system in
  64267. * @param rootUrl The root url to use to load external dependencies like texture
  64268. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  64269. * @returns the parsed GPU particle system
  64270. */
  64271. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  64272. if (doNotStart === void 0) { doNotStart = false; }
  64273. var name = parsedParticleSystem.name;
  64274. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64275. if (parsedParticleSystem.activeParticleCount) {
  64276. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64277. }
  64278. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64279. // Auto start
  64280. if (parsedParticleSystem.preventAutoStart) {
  64281. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  64282. }
  64283. if (!doNotStart && !particleSystem.preventAutoStart) {
  64284. particleSystem.start();
  64285. }
  64286. return particleSystem;
  64287. };
  64288. return GPUParticleSystem;
  64289. }(BABYLON.BaseParticleSystem));
  64290. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64291. })(BABYLON || (BABYLON = {}));
  64292. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64293. var BABYLON;
  64294. (function (BABYLON) {
  64295. /**
  64296. * Represents one particle of a solid particle system.
  64297. */
  64298. var SolidParticle = /** @class */ (function () {
  64299. /**
  64300. * Creates a Solid Particle object.
  64301. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64302. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64303. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64304. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64305. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64306. * @param shapeId (integer) is the model shape identifier in the SPS.
  64307. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64308. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64309. */
  64310. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64311. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64312. /**
  64313. * particle global index
  64314. */
  64315. this.idx = 0;
  64316. /**
  64317. * The color of the particle
  64318. */
  64319. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64320. /**
  64321. * The world space position of the particle.
  64322. */
  64323. this.position = BABYLON.Vector3.Zero();
  64324. /**
  64325. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64326. */
  64327. this.rotation = BABYLON.Vector3.Zero();
  64328. /**
  64329. * The scaling of the particle.
  64330. */
  64331. this.scaling = BABYLON.Vector3.One();
  64332. /**
  64333. * The uvs of the particle.
  64334. */
  64335. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64336. /**
  64337. * The current speed of the particle.
  64338. */
  64339. this.velocity = BABYLON.Vector3.Zero();
  64340. /**
  64341. * The pivot point in the particle local space.
  64342. */
  64343. this.pivot = BABYLON.Vector3.Zero();
  64344. /**
  64345. * Must the particle be translated from its pivot point in its local space ?
  64346. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64347. * Default : false
  64348. */
  64349. this.translateFromPivot = false;
  64350. /**
  64351. * Is the particle active or not ?
  64352. */
  64353. this.alive = true;
  64354. /**
  64355. * Is the particle visible or not ?
  64356. */
  64357. this.isVisible = true;
  64358. /**
  64359. * Index of this particle in the global "positions" array (Internal use)
  64360. * @hidden
  64361. */
  64362. this._pos = 0;
  64363. /**
  64364. * @hidden Index of this particle in the global "indices" array (Internal use)
  64365. */
  64366. this._ind = 0;
  64367. /**
  64368. * ModelShape id of this particle
  64369. */
  64370. this.shapeId = 0;
  64371. /**
  64372. * Index of the particle in its shape id (Internal use)
  64373. */
  64374. this.idxInShape = 0;
  64375. /**
  64376. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64377. */
  64378. this._stillInvisible = false;
  64379. /**
  64380. * @hidden Last computed particle rotation matrix
  64381. */
  64382. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64383. /**
  64384. * Parent particle Id, if any.
  64385. * Default null.
  64386. */
  64387. this.parentId = null;
  64388. /**
  64389. * @hidden Internal global position in the SPS.
  64390. */
  64391. this._globalPosition = BABYLON.Vector3.Zero();
  64392. this.idx = particleIndex;
  64393. this._pos = positionIndex;
  64394. this._ind = indiceIndex;
  64395. this._model = model;
  64396. this.shapeId = shapeId;
  64397. this.idxInShape = idxInShape;
  64398. this._sps = sps;
  64399. if (modelBoundingInfo) {
  64400. this._modelBoundingInfo = modelBoundingInfo;
  64401. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64402. }
  64403. }
  64404. Object.defineProperty(SolidParticle.prototype, "scale", {
  64405. /**
  64406. * Legacy support, changed scale to scaling
  64407. */
  64408. get: function () {
  64409. return this.scaling;
  64410. },
  64411. /**
  64412. * Legacy support, changed scale to scaling
  64413. */
  64414. set: function (scale) {
  64415. this.scaling = scale;
  64416. },
  64417. enumerable: true,
  64418. configurable: true
  64419. });
  64420. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64421. /**
  64422. * Legacy support, changed quaternion to rotationQuaternion
  64423. */
  64424. get: function () {
  64425. return this.rotationQuaternion;
  64426. },
  64427. /**
  64428. * Legacy support, changed quaternion to rotationQuaternion
  64429. */
  64430. set: function (q) {
  64431. this.rotationQuaternion = q;
  64432. },
  64433. enumerable: true,
  64434. configurable: true
  64435. });
  64436. /**
  64437. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64438. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64439. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64440. * @returns true if it intersects
  64441. */
  64442. SolidParticle.prototype.intersectsMesh = function (target) {
  64443. if (!this._boundingInfo || !target._boundingInfo) {
  64444. return false;
  64445. }
  64446. if (this._sps._bSphereOnly) {
  64447. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64448. }
  64449. return this._boundingInfo.intersects(target._boundingInfo, false);
  64450. };
  64451. return SolidParticle;
  64452. }());
  64453. BABYLON.SolidParticle = SolidParticle;
  64454. /**
  64455. * Represents the shape of the model used by one particle of a solid particle system.
  64456. * SPS internal tool, don't use it manually.
  64457. */
  64458. var ModelShape = /** @class */ (function () {
  64459. /**
  64460. * 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.
  64461. * SPS internal tool, don't use it manually.
  64462. * @hidden
  64463. */
  64464. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64465. /**
  64466. * length of the shape in the model indices array (internal use)
  64467. * @hidden
  64468. */
  64469. this._indicesLength = 0;
  64470. this.shapeID = id;
  64471. this._shape = shape;
  64472. this._indicesLength = indicesLength;
  64473. this._shapeUV = shapeUV;
  64474. this._positionFunction = posFunction;
  64475. this._vertexFunction = vtxFunction;
  64476. }
  64477. return ModelShape;
  64478. }());
  64479. BABYLON.ModelShape = ModelShape;
  64480. /**
  64481. * Represents a Depth Sorted Particle in the solid particle system.
  64482. */
  64483. var DepthSortedParticle = /** @class */ (function () {
  64484. function DepthSortedParticle() {
  64485. /**
  64486. * Index of the particle in the "indices" array
  64487. */
  64488. this.ind = 0;
  64489. /**
  64490. * Length of the particle shape in the "indices" array
  64491. */
  64492. this.indicesLength = 0;
  64493. /**
  64494. * Squared distance from the particle to the camera
  64495. */
  64496. this.sqDistance = 0.0;
  64497. }
  64498. return DepthSortedParticle;
  64499. }());
  64500. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64501. })(BABYLON || (BABYLON = {}));
  64502. //# sourceMappingURL=babylon.solidParticle.js.map
  64503. var BABYLON;
  64504. (function (BABYLON) {
  64505. /**
  64506. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64507. *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.
  64508. * The SPS is also a particle system. It provides some methods to manage the particles.
  64509. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64510. *
  64511. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64512. */
  64513. var SolidParticleSystem = /** @class */ (function () {
  64514. /**
  64515. * Creates a SPS (Solid Particle System) object.
  64516. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64517. * @param scene (Scene) is the scene in which the SPS is added.
  64518. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64519. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64520. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64521. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64522. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64523. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64524. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64525. */
  64526. function SolidParticleSystem(name, scene, options) {
  64527. /**
  64528. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64529. * Example : var p = SPS.particles[i];
  64530. */
  64531. this.particles = new Array();
  64532. /**
  64533. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64534. */
  64535. this.nbParticles = 0;
  64536. /**
  64537. * If the particles must ever face the camera (default false). Useful for planar particles.
  64538. */
  64539. this.billboard = false;
  64540. /**
  64541. * Recompute normals when adding a shape
  64542. */
  64543. this.recomputeNormals = true;
  64544. /**
  64545. * This a counter ofr your own usage. It's not set by any SPS functions.
  64546. */
  64547. this.counter = 0;
  64548. /**
  64549. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64550. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64551. */
  64552. this.vars = {};
  64553. /**
  64554. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64555. * @hidden
  64556. */
  64557. this._bSphereOnly = false;
  64558. /**
  64559. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64560. * @hidden
  64561. */
  64562. this._bSphereRadiusFactor = 1.0;
  64563. this._positions = new Array();
  64564. this._indices = new Array();
  64565. this._normals = new Array();
  64566. this._colors = new Array();
  64567. this._uvs = new Array();
  64568. this._index = 0; // indices index
  64569. this._updatable = true;
  64570. this._pickable = false;
  64571. this._isVisibilityBoxLocked = false;
  64572. this._alwaysVisible = false;
  64573. this._depthSort = false;
  64574. this._shapeCounter = 0;
  64575. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64576. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64577. this._computeParticleColor = true;
  64578. this._computeParticleTexture = true;
  64579. this._computeParticleRotation = true;
  64580. this._computeParticleVertex = false;
  64581. this._computeBoundingBox = false;
  64582. this._depthSortParticles = true;
  64583. this._cam_axisZ = BABYLON.Vector3.Zero();
  64584. this._cam_axisY = BABYLON.Vector3.Zero();
  64585. this._cam_axisX = BABYLON.Vector3.Zero();
  64586. this._axisZ = BABYLON.Axis.Z;
  64587. this._camDir = BABYLON.Vector3.Zero();
  64588. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64589. this._rotMatrix = new BABYLON.Matrix();
  64590. this._invertMatrix = new BABYLON.Matrix();
  64591. this._rotated = BABYLON.Vector3.Zero();
  64592. this._quaternion = new BABYLON.Quaternion();
  64593. this._vertex = BABYLON.Vector3.Zero();
  64594. this._normal = BABYLON.Vector3.Zero();
  64595. this._yaw = 0.0;
  64596. this._pitch = 0.0;
  64597. this._roll = 0.0;
  64598. this._halfroll = 0.0;
  64599. this._halfpitch = 0.0;
  64600. this._halfyaw = 0.0;
  64601. this._sinRoll = 0.0;
  64602. this._cosRoll = 0.0;
  64603. this._sinPitch = 0.0;
  64604. this._cosPitch = 0.0;
  64605. this._sinYaw = 0.0;
  64606. this._cosYaw = 0.0;
  64607. this._mustUnrotateFixedNormals = false;
  64608. this._minimum = BABYLON.Vector3.Zero();
  64609. this._maximum = BABYLON.Vector3.Zero();
  64610. this._minBbox = BABYLON.Vector3.Zero();
  64611. this._maxBbox = BABYLON.Vector3.Zero();
  64612. this._particlesIntersect = false;
  64613. this._depthSortFunction = function (p1, p2) {
  64614. return (p2.sqDistance - p1.sqDistance);
  64615. };
  64616. this._needs32Bits = false;
  64617. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64618. this._scaledPivot = BABYLON.Vector3.Zero();
  64619. this._particleHasParent = false;
  64620. this.name = name;
  64621. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64622. this._camera = scene.activeCamera;
  64623. this._pickable = options ? options.isPickable : false;
  64624. this._depthSort = options ? options.enableDepthSort : false;
  64625. this._particlesIntersect = options ? options.particleIntersection : false;
  64626. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64627. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64628. if (options && options.updatable !== undefined) {
  64629. this._updatable = options.updatable;
  64630. }
  64631. else {
  64632. this._updatable = true;
  64633. }
  64634. if (this._pickable) {
  64635. this.pickedParticles = [];
  64636. }
  64637. if (this._depthSort) {
  64638. this.depthSortedParticles = [];
  64639. }
  64640. }
  64641. /**
  64642. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64643. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64644. * @returns the created mesh
  64645. */
  64646. SolidParticleSystem.prototype.buildMesh = function () {
  64647. if (this.nbParticles === 0) {
  64648. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64649. this.addShape(triangle, 1);
  64650. triangle.dispose();
  64651. }
  64652. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64653. this._positions32 = new Float32Array(this._positions);
  64654. this._uvs32 = new Float32Array(this._uvs);
  64655. this._colors32 = new Float32Array(this._colors);
  64656. if (this.recomputeNormals) {
  64657. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64658. }
  64659. this._normals32 = new Float32Array(this._normals);
  64660. this._fixedNormal32 = new Float32Array(this._normals);
  64661. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64662. this._unrotateFixedNormals();
  64663. }
  64664. var vertexData = new BABYLON.VertexData();
  64665. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64666. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64667. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64668. if (this._uvs32.length > 0) {
  64669. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64670. }
  64671. if (this._colors32.length > 0) {
  64672. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64673. }
  64674. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64675. vertexData.applyToMesh(mesh, this._updatable);
  64676. this.mesh = mesh;
  64677. this.mesh.isPickable = this._pickable;
  64678. // free memory
  64679. if (!this._depthSort) {
  64680. this._indices = null;
  64681. }
  64682. this._positions = null;
  64683. this._normals = null;
  64684. this._uvs = null;
  64685. this._colors = null;
  64686. if (!this._updatable) {
  64687. this.particles.length = 0;
  64688. }
  64689. return mesh;
  64690. };
  64691. /**
  64692. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64693. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64694. * Thus the particles generated from `digest()` have their property `position` set yet.
  64695. * @param mesh ( Mesh ) is the mesh to be digested
  64696. * @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
  64697. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64698. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64699. * @returns the current SPS
  64700. */
  64701. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64702. var size = (options && options.facetNb) || 1;
  64703. var number = (options && options.number) || 0;
  64704. var delta = (options && options.delta) || 0;
  64705. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64706. var meshInd = mesh.getIndices();
  64707. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64708. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64709. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64710. var f = 0; // facet counter
  64711. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64712. // compute size from number
  64713. if (number) {
  64714. number = (number > totalFacets) ? totalFacets : number;
  64715. size = Math.round(totalFacets / number);
  64716. delta = 0;
  64717. }
  64718. else {
  64719. size = (size > totalFacets) ? totalFacets : size;
  64720. }
  64721. var facetPos = []; // submesh positions
  64722. var facetInd = []; // submesh indices
  64723. var facetUV = []; // submesh UV
  64724. var facetCol = []; // submesh colors
  64725. var barycenter = BABYLON.Vector3.Zero();
  64726. var sizeO = size;
  64727. while (f < totalFacets) {
  64728. size = sizeO + Math.floor((1 + delta) * Math.random());
  64729. if (f > totalFacets - size) {
  64730. size = totalFacets - f;
  64731. }
  64732. // reset temp arrays
  64733. facetPos.length = 0;
  64734. facetInd.length = 0;
  64735. facetUV.length = 0;
  64736. facetCol.length = 0;
  64737. // iterate over "size" facets
  64738. var fi = 0;
  64739. for (var j = f * 3; j < (f + size) * 3; j++) {
  64740. facetInd.push(fi);
  64741. var i = meshInd[j];
  64742. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64743. if (meshUV) {
  64744. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64745. }
  64746. if (meshCol) {
  64747. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64748. }
  64749. fi++;
  64750. }
  64751. // create a model shape for each single particle
  64752. var idx = this.nbParticles;
  64753. var shape = this._posToShape(facetPos);
  64754. var shapeUV = this._uvsToShapeUV(facetUV);
  64755. // compute the barycenter of the shape
  64756. var v;
  64757. for (v = 0; v < shape.length; v++) {
  64758. barycenter.addInPlace(shape[v]);
  64759. }
  64760. barycenter.scaleInPlace(1 / shape.length);
  64761. // shift the shape from its barycenter to the origin
  64762. for (v = 0; v < shape.length; v++) {
  64763. shape[v].subtractInPlace(barycenter);
  64764. }
  64765. var bInfo;
  64766. if (this._particlesIntersect) {
  64767. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64768. }
  64769. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64770. // add the particle in the SPS
  64771. var currentPos = this._positions.length;
  64772. var currentInd = this._indices.length;
  64773. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64774. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64775. // initialize the particle position
  64776. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64777. this._index += shape.length;
  64778. idx++;
  64779. this.nbParticles++;
  64780. this._shapeCounter++;
  64781. f += size;
  64782. }
  64783. return this;
  64784. };
  64785. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64786. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64787. var index = 0;
  64788. var idx = 0;
  64789. for (var p = 0; p < this.particles.length; p++) {
  64790. this._particle = this.particles[p];
  64791. this._shape = this._particle._model._shape;
  64792. if (this._particle.rotationQuaternion) {
  64793. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64794. }
  64795. else {
  64796. this._yaw = this._particle.rotation.y;
  64797. this._pitch = this._particle.rotation.x;
  64798. this._roll = this._particle.rotation.z;
  64799. this._quaternionRotationYPR();
  64800. }
  64801. this._quaternionToRotationMatrix();
  64802. this._rotMatrix.invertToRef(this._invertMatrix);
  64803. for (var pt = 0; pt < this._shape.length; pt++) {
  64804. idx = index + pt * 3;
  64805. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64806. this._fixedNormal32[idx] = this._normal.x;
  64807. this._fixedNormal32[idx + 1] = this._normal.y;
  64808. this._fixedNormal32[idx + 2] = this._normal.z;
  64809. }
  64810. index = idx + 3;
  64811. }
  64812. };
  64813. //reset copy
  64814. SolidParticleSystem.prototype._resetCopy = function () {
  64815. this._copy.position.x = 0;
  64816. this._copy.position.y = 0;
  64817. this._copy.position.z = 0;
  64818. this._copy.rotation.x = 0;
  64819. this._copy.rotation.y = 0;
  64820. this._copy.rotation.z = 0;
  64821. this._copy.rotationQuaternion = null;
  64822. this._copy.scaling.x = 1.0;
  64823. this._copy.scaling.y = 1.0;
  64824. this._copy.scaling.z = 1.0;
  64825. this._copy.uvs.x = 0;
  64826. this._copy.uvs.y = 0;
  64827. this._copy.uvs.z = 1.0;
  64828. this._copy.uvs.w = 1.0;
  64829. this._copy.color = null;
  64830. this._copy.translateFromPivot = false;
  64831. };
  64832. // _meshBuilder : inserts the shape model in the global SPS mesh
  64833. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64834. var i;
  64835. var u = 0;
  64836. var c = 0;
  64837. var n = 0;
  64838. this._resetCopy();
  64839. if (options && options.positionFunction) { // call to custom positionFunction
  64840. options.positionFunction(this._copy, idx, idxInShape);
  64841. this._mustUnrotateFixedNormals = true;
  64842. }
  64843. if (this._copy.rotationQuaternion) {
  64844. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64845. }
  64846. else {
  64847. this._yaw = this._copy.rotation.y;
  64848. this._pitch = this._copy.rotation.x;
  64849. this._roll = this._copy.rotation.z;
  64850. this._quaternionRotationYPR();
  64851. }
  64852. this._quaternionToRotationMatrix();
  64853. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64854. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64855. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64856. if (this._copy.translateFromPivot) {
  64857. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64858. }
  64859. else {
  64860. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64861. }
  64862. for (i = 0; i < shape.length; i++) {
  64863. this._vertex.x = shape[i].x;
  64864. this._vertex.y = shape[i].y;
  64865. this._vertex.z = shape[i].z;
  64866. if (options && options.vertexFunction) {
  64867. options.vertexFunction(this._copy, this._vertex, i);
  64868. }
  64869. this._vertex.x *= this._copy.scaling.x;
  64870. this._vertex.y *= this._copy.scaling.y;
  64871. this._vertex.z *= this._copy.scaling.z;
  64872. this._vertex.x -= this._scaledPivot.x;
  64873. this._vertex.y -= this._scaledPivot.y;
  64874. this._vertex.z -= this._scaledPivot.z;
  64875. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64876. this._rotated.addInPlace(this._pivotBackTranslation);
  64877. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64878. if (meshUV) {
  64879. 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);
  64880. u += 2;
  64881. }
  64882. if (this._copy.color) {
  64883. this._color = this._copy.color;
  64884. }
  64885. else if (meshCol && meshCol[c] !== undefined) {
  64886. this._color.r = meshCol[c];
  64887. this._color.g = meshCol[c + 1];
  64888. this._color.b = meshCol[c + 2];
  64889. this._color.a = meshCol[c + 3];
  64890. }
  64891. else {
  64892. this._color.r = 1.0;
  64893. this._color.g = 1.0;
  64894. this._color.b = 1.0;
  64895. this._color.a = 1.0;
  64896. }
  64897. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64898. c += 4;
  64899. if (!this.recomputeNormals && meshNor) {
  64900. this._normal.x = meshNor[n];
  64901. this._normal.y = meshNor[n + 1];
  64902. this._normal.z = meshNor[n + 2];
  64903. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64904. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64905. n += 3;
  64906. }
  64907. }
  64908. for (i = 0; i < meshInd.length; i++) {
  64909. var current_ind = p + meshInd[i];
  64910. indices.push(current_ind);
  64911. if (current_ind > 65535) {
  64912. this._needs32Bits = true;
  64913. }
  64914. }
  64915. if (this._pickable) {
  64916. var nbfaces = meshInd.length / 3;
  64917. for (i = 0; i < nbfaces; i++) {
  64918. this.pickedParticles.push({ idx: idx, faceId: i });
  64919. }
  64920. }
  64921. if (this._depthSort) {
  64922. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64923. }
  64924. return this._copy;
  64925. };
  64926. // returns a shape array from positions array
  64927. SolidParticleSystem.prototype._posToShape = function (positions) {
  64928. var shape = [];
  64929. for (var i = 0; i < positions.length; i += 3) {
  64930. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64931. }
  64932. return shape;
  64933. };
  64934. // returns a shapeUV array from a Vector4 uvs
  64935. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64936. var shapeUV = [];
  64937. if (uvs) {
  64938. for (var i = 0; i < uvs.length; i++)
  64939. shapeUV.push(uvs[i]);
  64940. }
  64941. return shapeUV;
  64942. };
  64943. // adds a new particle object in the particles array
  64944. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64945. if (bInfo === void 0) { bInfo = null; }
  64946. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64947. this.particles.push(sp);
  64948. return sp;
  64949. };
  64950. /**
  64951. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64952. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64953. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64954. * @param nb (positive integer) the number of particles to be created from this model
  64955. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64956. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64957. * @returns the number of shapes in the system
  64958. */
  64959. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64960. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64961. var meshInd = mesh.getIndices();
  64962. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64963. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64964. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64965. var bbInfo;
  64966. if (this._particlesIntersect) {
  64967. bbInfo = mesh.getBoundingInfo();
  64968. }
  64969. var shape = this._posToShape(meshPos);
  64970. var shapeUV = this._uvsToShapeUV(meshUV);
  64971. var posfunc = options ? options.positionFunction : null;
  64972. var vtxfunc = options ? options.vertexFunction : null;
  64973. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  64974. // particles
  64975. var sp;
  64976. var currentCopy;
  64977. var idx = this.nbParticles;
  64978. for (var i = 0; i < nb; i++) {
  64979. var currentPos = this._positions.length;
  64980. var currentInd = this._indices.length;
  64981. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  64982. if (this._updatable) {
  64983. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  64984. sp.position.copyFrom(currentCopy.position);
  64985. sp.rotation.copyFrom(currentCopy.rotation);
  64986. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  64987. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  64988. }
  64989. if (currentCopy.color && sp.color) {
  64990. sp.color.copyFrom(currentCopy.color);
  64991. }
  64992. sp.scaling.copyFrom(currentCopy.scaling);
  64993. sp.uvs.copyFrom(currentCopy.uvs);
  64994. }
  64995. this._index += shape.length;
  64996. idx++;
  64997. }
  64998. this.nbParticles += nb;
  64999. this._shapeCounter++;
  65000. return this._shapeCounter - 1;
  65001. };
  65002. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65003. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65004. this._resetCopy();
  65005. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65006. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65007. }
  65008. if (this._copy.rotationQuaternion) {
  65009. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65010. }
  65011. else {
  65012. this._yaw = this._copy.rotation.y;
  65013. this._pitch = this._copy.rotation.x;
  65014. this._roll = this._copy.rotation.z;
  65015. this._quaternionRotationYPR();
  65016. }
  65017. this._quaternionToRotationMatrix();
  65018. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65019. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65020. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65021. if (this._copy.translateFromPivot) {
  65022. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65023. }
  65024. else {
  65025. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65026. }
  65027. this._shape = particle._model._shape;
  65028. for (var pt = 0; pt < this._shape.length; pt++) {
  65029. this._vertex.x = this._shape[pt].x;
  65030. this._vertex.y = this._shape[pt].y;
  65031. this._vertex.z = this._shape[pt].z;
  65032. if (particle._model._vertexFunction) {
  65033. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65034. }
  65035. this._vertex.x *= this._copy.scaling.x;
  65036. this._vertex.y *= this._copy.scaling.y;
  65037. this._vertex.z *= this._copy.scaling.z;
  65038. this._vertex.x -= this._scaledPivot.x;
  65039. this._vertex.y -= this._scaledPivot.y;
  65040. this._vertex.z -= this._scaledPivot.z;
  65041. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65042. this._rotated.addInPlace(this._pivotBackTranslation);
  65043. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65044. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65045. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65046. }
  65047. particle.position.x = 0.0;
  65048. particle.position.y = 0.0;
  65049. particle.position.z = 0.0;
  65050. particle.rotation.x = 0.0;
  65051. particle.rotation.y = 0.0;
  65052. particle.rotation.z = 0.0;
  65053. particle.rotationQuaternion = null;
  65054. particle.scaling.x = 1.0;
  65055. particle.scaling.y = 1.0;
  65056. particle.scaling.z = 1.0;
  65057. particle.uvs.x = 0.0;
  65058. particle.uvs.y = 0.0;
  65059. particle.uvs.z = 1.0;
  65060. particle.uvs.w = 1.0;
  65061. particle.pivot.x = 0.0;
  65062. particle.pivot.y = 0.0;
  65063. particle.pivot.z = 0.0;
  65064. particle.translateFromPivot = false;
  65065. particle.parentId = null;
  65066. };
  65067. /**
  65068. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65069. * @returns the SPS.
  65070. */
  65071. SolidParticleSystem.prototype.rebuildMesh = function () {
  65072. for (var p = 0; p < this.particles.length; p++) {
  65073. this._rebuildParticle(this.particles[p]);
  65074. }
  65075. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65076. return this;
  65077. };
  65078. /**
  65079. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65080. * This method calls `updateParticle()` for each particle of the SPS.
  65081. * For an animated SPS, it is usually called within the render loop.
  65082. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  65083. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  65084. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  65085. * @returns the SPS.
  65086. */
  65087. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  65088. if (start === void 0) { start = 0; }
  65089. if (end === void 0) { end = this.nbParticles - 1; }
  65090. if (update === void 0) { update = true; }
  65091. if (!this._updatable) {
  65092. return this;
  65093. }
  65094. // custom beforeUpdate
  65095. this.beforeUpdateParticles(start, end, update);
  65096. this._cam_axisX.x = 1.0;
  65097. this._cam_axisX.y = 0.0;
  65098. this._cam_axisX.z = 0.0;
  65099. this._cam_axisY.x = 0.0;
  65100. this._cam_axisY.y = 1.0;
  65101. this._cam_axisY.z = 0.0;
  65102. this._cam_axisZ.x = 0.0;
  65103. this._cam_axisZ.y = 0.0;
  65104. this._cam_axisZ.z = 1.0;
  65105. // cases when the World Matrix is to be computed first
  65106. if (this.billboard || this._depthSort) {
  65107. this.mesh.computeWorldMatrix(true);
  65108. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  65109. }
  65110. // if the particles will always face the camera
  65111. if (this.billboard) {
  65112. // compute the camera position and un-rotate it by the current mesh rotation
  65113. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  65114. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  65115. this._cam_axisZ.normalize();
  65116. // same for camera up vector extracted from the cam view matrix
  65117. var view = this._camera.getViewMatrix(true);
  65118. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  65119. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  65120. this._cam_axisY.normalize();
  65121. this._cam_axisX.normalize();
  65122. }
  65123. // if depthSort, compute the camera global position in the mesh local system
  65124. if (this._depthSort) {
  65125. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  65126. }
  65127. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  65128. var idx = 0; // current position index in the global array positions32
  65129. var index = 0; // position start index in the global array positions32 of the current particle
  65130. var colidx = 0; // current color index in the global array colors32
  65131. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  65132. var uvidx = 0; // current uv index in the global array uvs32
  65133. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  65134. var pt = 0; // current index in the particle model shape
  65135. if (this.mesh.isFacetDataEnabled) {
  65136. this._computeBoundingBox = true;
  65137. }
  65138. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  65139. if (this._computeBoundingBox) {
  65140. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  65141. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  65142. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  65143. }
  65144. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  65145. if (this.mesh._boundingInfo) {
  65146. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  65147. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  65148. }
  65149. }
  65150. }
  65151. // particle loop
  65152. index = this.particles[start]._pos;
  65153. var vpos = (index / 3) | 0;
  65154. colorIndex = vpos * 4;
  65155. uvIndex = vpos * 2;
  65156. for (var p = start; p <= end; p++) {
  65157. this._particle = this.particles[p];
  65158. this._shape = this._particle._model._shape;
  65159. this._shapeUV = this._particle._model._shapeUV;
  65160. // call to custom user function to update the particle properties
  65161. this.updateParticle(this._particle);
  65162. // camera-particle distance for depth sorting
  65163. if (this._depthSort && this._depthSortParticles) {
  65164. var dsp = this.depthSortedParticles[p];
  65165. dsp.ind = this._particle._ind;
  65166. dsp.indicesLength = this._particle._model._indicesLength;
  65167. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  65168. }
  65169. // skip the computations for inactive or already invisible particles
  65170. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  65171. // increment indexes for the next particle
  65172. pt = this._shape.length;
  65173. index += pt * 3;
  65174. colorIndex += pt * 4;
  65175. uvIndex += pt * 2;
  65176. continue;
  65177. }
  65178. if (this._particle.isVisible) {
  65179. this._particle._stillInvisible = false; // un-mark permanent invisibility
  65180. this._particleHasParent = (this._particle.parentId !== null);
  65181. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65182. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65183. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65184. // particle rotation matrix
  65185. if (this.billboard) {
  65186. this._particle.rotation.x = 0.0;
  65187. this._particle.rotation.y = 0.0;
  65188. }
  65189. if (this._computeParticleRotation || this.billboard) {
  65190. if (this._particle.rotationQuaternion) {
  65191. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65192. }
  65193. else {
  65194. this._yaw = this._particle.rotation.y;
  65195. this._pitch = this._particle.rotation.x;
  65196. this._roll = this._particle.rotation.z;
  65197. this._quaternionRotationYPR();
  65198. }
  65199. this._quaternionToRotationMatrix();
  65200. }
  65201. if (this._particleHasParent) {
  65202. this._parent = this.particles[this._particle.parentId];
  65203. 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];
  65204. 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];
  65205. 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];
  65206. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  65207. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  65208. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  65209. if (this._computeParticleRotation || this.billboard) {
  65210. 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];
  65211. 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];
  65212. 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];
  65213. 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];
  65214. 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];
  65215. 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];
  65216. 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];
  65217. 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];
  65218. 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];
  65219. }
  65220. }
  65221. else {
  65222. this._particle._globalPosition.x = this._particle.position.x;
  65223. this._particle._globalPosition.y = this._particle.position.y;
  65224. this._particle._globalPosition.z = this._particle.position.z;
  65225. if (this._computeParticleRotation || this.billboard) {
  65226. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  65227. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  65228. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  65229. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  65230. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  65231. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  65232. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  65233. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  65234. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  65235. }
  65236. }
  65237. if (this._particle.translateFromPivot) {
  65238. this._pivotBackTranslation.x = 0.0;
  65239. this._pivotBackTranslation.y = 0.0;
  65240. this._pivotBackTranslation.z = 0.0;
  65241. }
  65242. else {
  65243. this._pivotBackTranslation.x = this._scaledPivot.x;
  65244. this._pivotBackTranslation.y = this._scaledPivot.y;
  65245. this._pivotBackTranslation.z = this._scaledPivot.z;
  65246. }
  65247. // particle vertex loop
  65248. for (pt = 0; pt < this._shape.length; pt++) {
  65249. idx = index + pt * 3;
  65250. colidx = colorIndex + pt * 4;
  65251. uvidx = uvIndex + pt * 2;
  65252. this._vertex.x = this._shape[pt].x;
  65253. this._vertex.y = this._shape[pt].y;
  65254. this._vertex.z = this._shape[pt].z;
  65255. if (this._computeParticleVertex) {
  65256. this.updateParticleVertex(this._particle, this._vertex, pt);
  65257. }
  65258. // positions
  65259. this._vertex.x *= this._particle.scaling.x;
  65260. this._vertex.y *= this._particle.scaling.y;
  65261. this._vertex.z *= this._particle.scaling.z;
  65262. this._vertex.x -= this._scaledPivot.x;
  65263. this._vertex.y -= this._scaledPivot.y;
  65264. this._vertex.z -= this._scaledPivot.z;
  65265. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65266. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65267. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65268. this._rotated.x += this._pivotBackTranslation.x;
  65269. this._rotated.y += this._pivotBackTranslation.y;
  65270. this._rotated.z += this._pivotBackTranslation.z;
  65271. 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;
  65272. 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;
  65273. 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;
  65274. if (this._computeBoundingBox) {
  65275. if (this._positions32[idx] < this._minimum.x) {
  65276. this._minimum.x = this._positions32[idx];
  65277. }
  65278. if (this._positions32[idx] > this._maximum.x) {
  65279. this._maximum.x = this._positions32[idx];
  65280. }
  65281. if (this._positions32[idx + 1] < this._minimum.y) {
  65282. this._minimum.y = this._positions32[idx + 1];
  65283. }
  65284. if (this._positions32[idx + 1] > this._maximum.y) {
  65285. this._maximum.y = this._positions32[idx + 1];
  65286. }
  65287. if (this._positions32[idx + 2] < this._minimum.z) {
  65288. this._minimum.z = this._positions32[idx + 2];
  65289. }
  65290. if (this._positions32[idx + 2] > this._maximum.z) {
  65291. this._maximum.z = this._positions32[idx + 2];
  65292. }
  65293. }
  65294. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65295. if (!this._computeParticleVertex) {
  65296. this._normal.x = this._fixedNormal32[idx];
  65297. this._normal.y = this._fixedNormal32[idx + 1];
  65298. this._normal.z = this._fixedNormal32[idx + 2];
  65299. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65300. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65301. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65302. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65303. 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;
  65304. 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;
  65305. }
  65306. if (this._computeParticleColor && this._particle.color) {
  65307. this._colors32[colidx] = this._particle.color.r;
  65308. this._colors32[colidx + 1] = this._particle.color.g;
  65309. this._colors32[colidx + 2] = this._particle.color.b;
  65310. this._colors32[colidx + 3] = this._particle.color.a;
  65311. }
  65312. if (this._computeParticleTexture) {
  65313. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65314. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65315. }
  65316. }
  65317. }
  65318. // particle just set invisible : scaled to zero and positioned at the origin
  65319. else {
  65320. this._particle._stillInvisible = true; // mark the particle as invisible
  65321. for (pt = 0; pt < this._shape.length; pt++) {
  65322. idx = index + pt * 3;
  65323. colidx = colorIndex + pt * 4;
  65324. uvidx = uvIndex + pt * 2;
  65325. this._positions32[idx] = 0.0;
  65326. this._positions32[idx + 1] = 0.0;
  65327. this._positions32[idx + 2] = 0.0;
  65328. this._normals32[idx] = 0.0;
  65329. this._normals32[idx + 1] = 0.0;
  65330. this._normals32[idx + 2] = 0.0;
  65331. if (this._computeParticleColor && this._particle.color) {
  65332. this._colors32[colidx] = this._particle.color.r;
  65333. this._colors32[colidx + 1] = this._particle.color.g;
  65334. this._colors32[colidx + 2] = this._particle.color.b;
  65335. this._colors32[colidx + 3] = this._particle.color.a;
  65336. }
  65337. if (this._computeParticleTexture) {
  65338. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65339. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65340. }
  65341. }
  65342. }
  65343. // if the particle intersections must be computed : update the bbInfo
  65344. if (this._particlesIntersect) {
  65345. var bInfo = this._particle._boundingInfo;
  65346. var bBox = bInfo.boundingBox;
  65347. var bSphere = bInfo.boundingSphere;
  65348. if (!this._bSphereOnly) {
  65349. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65350. for (var b = 0; b < bBox.vectors.length; b++) {
  65351. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65352. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65353. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65354. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65355. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65356. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65357. 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;
  65358. 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;
  65359. 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;
  65360. }
  65361. bBox._update(this.mesh._worldMatrix);
  65362. }
  65363. // place and scale the particle bouding sphere in the SPS local system, then update it
  65364. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65365. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65366. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65367. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65368. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65369. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65370. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65371. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65372. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65373. 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));
  65374. bSphere._update(this.mesh._worldMatrix);
  65375. }
  65376. // increment indexes for the next particle
  65377. index = idx + 3;
  65378. colorIndex = colidx + 4;
  65379. uvIndex = uvidx + 2;
  65380. }
  65381. // if the VBO must be updated
  65382. if (update) {
  65383. if (this._computeParticleColor) {
  65384. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65385. }
  65386. if (this._computeParticleTexture) {
  65387. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65388. }
  65389. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65390. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65391. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65392. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65393. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65394. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65395. for (var i = 0; i < this._normals32.length; i++) {
  65396. this._fixedNormal32[i] = this._normals32[i];
  65397. }
  65398. }
  65399. if (!this.mesh.areNormalsFrozen) {
  65400. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65401. }
  65402. }
  65403. if (this._depthSort && this._depthSortParticles) {
  65404. this.depthSortedParticles.sort(this._depthSortFunction);
  65405. var dspl = this.depthSortedParticles.length;
  65406. var sorted = 0;
  65407. var lind = 0;
  65408. var sind = 0;
  65409. var sid = 0;
  65410. for (sorted = 0; sorted < dspl; sorted++) {
  65411. lind = this.depthSortedParticles[sorted].indicesLength;
  65412. sind = this.depthSortedParticles[sorted].ind;
  65413. for (var i = 0; i < lind; i++) {
  65414. this._indices32[sid] = this._indices[sind + i];
  65415. sid++;
  65416. }
  65417. }
  65418. this.mesh.updateIndices(this._indices32);
  65419. }
  65420. }
  65421. if (this._computeBoundingBox) {
  65422. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65423. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65424. }
  65425. this.afterUpdateParticles(start, end, update);
  65426. return this;
  65427. };
  65428. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65429. this._halfroll = this._roll * 0.5;
  65430. this._halfpitch = this._pitch * 0.5;
  65431. this._halfyaw = this._yaw * 0.5;
  65432. this._sinRoll = Math.sin(this._halfroll);
  65433. this._cosRoll = Math.cos(this._halfroll);
  65434. this._sinPitch = Math.sin(this._halfpitch);
  65435. this._cosPitch = Math.cos(this._halfpitch);
  65436. this._sinYaw = Math.sin(this._halfyaw);
  65437. this._cosYaw = Math.cos(this._halfyaw);
  65438. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65439. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65440. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65441. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65442. };
  65443. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65444. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65445. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65446. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65447. this._rotMatrix.m[3] = 0;
  65448. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65449. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65450. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65451. this._rotMatrix.m[7] = 0;
  65452. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65453. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65454. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65455. this._rotMatrix.m[11] = 0;
  65456. this._rotMatrix.m[12] = 0;
  65457. this._rotMatrix.m[13] = 0;
  65458. this._rotMatrix.m[14] = 0;
  65459. this._rotMatrix.m[15] = 1.0;
  65460. };
  65461. /**
  65462. * Disposes the SPS.
  65463. */
  65464. SolidParticleSystem.prototype.dispose = function () {
  65465. this.mesh.dispose();
  65466. this.vars = null;
  65467. // drop references to internal big arrays for the GC
  65468. this._positions = null;
  65469. this._indices = null;
  65470. this._normals = null;
  65471. this._uvs = null;
  65472. this._colors = null;
  65473. this._indices32 = null;
  65474. this._positions32 = null;
  65475. this._normals32 = null;
  65476. this._fixedNormal32 = null;
  65477. this._uvs32 = null;
  65478. this._colors32 = null;
  65479. this.pickedParticles = null;
  65480. };
  65481. /**
  65482. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65483. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65484. * @returns the SPS.
  65485. */
  65486. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65487. if (!this._isVisibilityBoxLocked) {
  65488. this.mesh.refreshBoundingInfo();
  65489. }
  65490. return this;
  65491. };
  65492. /**
  65493. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65494. * @param size the size (float) of the visibility box
  65495. * note : this doesn't lock the SPS mesh bounding box.
  65496. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65497. */
  65498. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65499. var vis = size / 2;
  65500. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65501. };
  65502. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65503. /**
  65504. * Gets whether the SPS as always visible or not
  65505. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65506. */
  65507. get: function () {
  65508. return this._alwaysVisible;
  65509. },
  65510. /**
  65511. * Sets the SPS as always visible or not
  65512. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65513. */
  65514. set: function (val) {
  65515. this._alwaysVisible = val;
  65516. this.mesh.alwaysSelectAsActiveMesh = val;
  65517. },
  65518. enumerable: true,
  65519. configurable: true
  65520. });
  65521. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65522. /**
  65523. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65524. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65525. */
  65526. get: function () {
  65527. return this._isVisibilityBoxLocked;
  65528. },
  65529. /**
  65530. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65531. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65532. */
  65533. set: function (val) {
  65534. this._isVisibilityBoxLocked = val;
  65535. var boundingInfo = this.mesh.getBoundingInfo();
  65536. boundingInfo.isLocked = val;
  65537. },
  65538. enumerable: true,
  65539. configurable: true
  65540. });
  65541. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65542. /**
  65543. * Gets if `setParticles()` computes the particle rotations or not.
  65544. * Default value : true. The SPS is faster when it's set to false.
  65545. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65546. */
  65547. get: function () {
  65548. return this._computeParticleRotation;
  65549. },
  65550. /**
  65551. * Tells to `setParticles()` to compute the particle rotations or not.
  65552. * Default value : true. The SPS is faster when it's set to false.
  65553. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65554. */
  65555. set: function (val) {
  65556. this._computeParticleRotation = val;
  65557. },
  65558. enumerable: true,
  65559. configurable: true
  65560. });
  65561. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65562. /**
  65563. * Gets if `setParticles()` computes the particle colors or not.
  65564. * Default value : true. The SPS is faster when it's set to false.
  65565. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65566. */
  65567. get: function () {
  65568. return this._computeParticleColor;
  65569. },
  65570. /**
  65571. * Tells to `setParticles()` to compute the particle colors or not.
  65572. * Default value : true. The SPS is faster when it's set to false.
  65573. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65574. */
  65575. set: function (val) {
  65576. this._computeParticleColor = val;
  65577. },
  65578. enumerable: true,
  65579. configurable: true
  65580. });
  65581. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65582. /**
  65583. * Gets if `setParticles()` computes the particle textures or not.
  65584. * Default value : true. The SPS is faster when it's set to false.
  65585. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65586. */
  65587. get: function () {
  65588. return this._computeParticleTexture;
  65589. },
  65590. set: function (val) {
  65591. this._computeParticleTexture = val;
  65592. },
  65593. enumerable: true,
  65594. configurable: true
  65595. });
  65596. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65597. /**
  65598. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65599. * Default value : false. The SPS is faster when it's set to false.
  65600. * Note : the particle custom vertex positions aren't stored values.
  65601. */
  65602. get: function () {
  65603. return this._computeParticleVertex;
  65604. },
  65605. /**
  65606. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65607. * Default value : false. The SPS is faster when it's set to false.
  65608. * Note : the particle custom vertex positions aren't stored values.
  65609. */
  65610. set: function (val) {
  65611. this._computeParticleVertex = val;
  65612. },
  65613. enumerable: true,
  65614. configurable: true
  65615. });
  65616. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65617. /**
  65618. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65619. */
  65620. get: function () {
  65621. return this._computeBoundingBox;
  65622. },
  65623. /**
  65624. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65625. */
  65626. set: function (val) {
  65627. this._computeBoundingBox = val;
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65633. /**
  65634. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65635. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65636. * Default : `true`
  65637. */
  65638. get: function () {
  65639. return this._depthSortParticles;
  65640. },
  65641. /**
  65642. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65643. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65644. * Default : `true`
  65645. */
  65646. set: function (val) {
  65647. this._depthSortParticles = val;
  65648. },
  65649. enumerable: true,
  65650. configurable: true
  65651. });
  65652. // =======================================================================
  65653. // Particle behavior logic
  65654. // these following methods may be overwritten by the user to fit his needs
  65655. /**
  65656. * This function does nothing. It may be overwritten to set all the particle first values.
  65657. * The SPS doesn't call this function, you may have to call it by your own.
  65658. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65659. */
  65660. SolidParticleSystem.prototype.initParticles = function () {
  65661. };
  65662. /**
  65663. * This function does nothing. It may be overwritten to recycle a particle.
  65664. * The SPS doesn't call this function, you may have to call it by your own.
  65665. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65666. * @param particle The particle to recycle
  65667. * @returns the recycled particle
  65668. */
  65669. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65670. return particle;
  65671. };
  65672. /**
  65673. * Updates a particle : this function should be overwritten by the user.
  65674. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65675. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65676. * @example : just set a particle position or velocity and recycle conditions
  65677. * @param particle The particle to update
  65678. * @returns the updated particle
  65679. */
  65680. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65681. return particle;
  65682. };
  65683. /**
  65684. * Updates a vertex of a particle : it can be overwritten by the user.
  65685. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65686. * @param particle the current particle
  65687. * @param vertex the current index of the current particle
  65688. * @param pt the index of the current vertex in the particle shape
  65689. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65690. * @example : just set a vertex particle position
  65691. * @returns the updated vertex
  65692. */
  65693. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65694. return vertex;
  65695. };
  65696. /**
  65697. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65698. * This does nothing and may be overwritten by the user.
  65699. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65700. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65701. * @param update the boolean update value actually passed to setParticles()
  65702. */
  65703. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65704. };
  65705. /**
  65706. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65707. * This will be passed three parameters.
  65708. * This does nothing and may be overwritten by the user.
  65709. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65710. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65711. * @param update the boolean update value actually passed to setParticles()
  65712. */
  65713. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65714. };
  65715. return SolidParticleSystem;
  65716. }());
  65717. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65718. })(BABYLON || (BABYLON = {}));
  65719. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65720. var BABYLON;
  65721. (function (BABYLON) {
  65722. /**
  65723. * Class containing static functions to help procedurally build meshes
  65724. */
  65725. var MeshBuilder = /** @class */ (function () {
  65726. function MeshBuilder() {
  65727. }
  65728. MeshBuilder.updateSideOrientation = function (orientation) {
  65729. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65730. return BABYLON.Mesh.DOUBLESIDE;
  65731. }
  65732. if (orientation === undefined || orientation === null) {
  65733. return BABYLON.Mesh.FRONTSIDE;
  65734. }
  65735. return orientation;
  65736. };
  65737. /**
  65738. * Creates a box mesh
  65739. * * The parameter `size` sets the size (float) of each box side (default 1)
  65740. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65741. * * 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)
  65742. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65743. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65744. * * 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
  65745. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65746. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65747. * @param name defines the name of the mesh
  65748. * @param options defines the options used to create the mesh
  65749. * @param scene defines the hosting scene
  65750. * @returns the box mesh
  65751. */
  65752. MeshBuilder.CreateBox = function (name, options, scene) {
  65753. if (scene === void 0) { scene = null; }
  65754. var box = new BABYLON.Mesh(name, scene);
  65755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65756. box._originalBuilderSideOrientation = options.sideOrientation;
  65757. var vertexData = BABYLON.VertexData.CreateBox(options);
  65758. vertexData.applyToMesh(box, options.updatable);
  65759. return box;
  65760. };
  65761. /**
  65762. * Creates a sphere mesh
  65763. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65764. * * 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`)
  65765. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65766. * * 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
  65767. * * 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)
  65768. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65769. * * 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
  65770. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65771. * @param name defines the name of the mesh
  65772. * @param options defines the options used to create the mesh
  65773. * @param scene defines the hosting scene
  65774. * @returns the sphere mesh
  65775. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65776. */
  65777. MeshBuilder.CreateSphere = function (name, options, scene) {
  65778. var sphere = new BABYLON.Mesh(name, scene);
  65779. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65780. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65781. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65782. vertexData.applyToMesh(sphere, options.updatable);
  65783. return sphere;
  65784. };
  65785. /**
  65786. * Creates a plane polygonal mesh. By default, this is a disc
  65787. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65788. * * 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
  65789. * * 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
  65790. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65791. * * 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
  65792. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65793. * @param name defines the name of the mesh
  65794. * @param options defines the options used to create the mesh
  65795. * @param scene defines the hosting scene
  65796. * @returns the plane polygonal mesh
  65797. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65798. */
  65799. MeshBuilder.CreateDisc = function (name, options, scene) {
  65800. if (scene === void 0) { scene = null; }
  65801. var disc = new BABYLON.Mesh(name, scene);
  65802. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65803. disc._originalBuilderSideOrientation = options.sideOrientation;
  65804. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65805. vertexData.applyToMesh(disc, options.updatable);
  65806. return disc;
  65807. };
  65808. /**
  65809. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65810. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65811. * * 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`)
  65812. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65813. * * 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
  65814. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65815. * * 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
  65816. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65817. * @param name defines the name of the mesh
  65818. * @param options defines the options used to create the mesh
  65819. * @param scene defines the hosting scene
  65820. * @returns the icosahedron mesh
  65821. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65822. */
  65823. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65824. var sphere = new BABYLON.Mesh(name, scene);
  65825. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65826. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65827. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65828. vertexData.applyToMesh(sphere, options.updatable);
  65829. return sphere;
  65830. };
  65831. ;
  65832. /**
  65833. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65834. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65835. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65836. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65837. * * 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
  65838. * * 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
  65839. * * 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
  65840. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65841. * * 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
  65842. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65843. * * 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
  65844. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65845. * * 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
  65846. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65847. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65848. * @param name defines the name of the mesh
  65849. * @param options defines the options used to create the mesh
  65850. * @param scene defines the hosting scene
  65851. * @returns the ribbon mesh
  65852. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65853. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65854. */
  65855. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65856. if (scene === void 0) { scene = null; }
  65857. var pathArray = options.pathArray;
  65858. var closeArray = options.closeArray;
  65859. var closePath = options.closePath;
  65860. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65861. var instance = options.instance;
  65862. var updatable = options.updatable;
  65863. if (instance) { // existing ribbon instance update
  65864. // positionFunction : ribbon case
  65865. // only pathArray and sideOrientation parameters are taken into account for positions update
  65866. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65867. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65868. var positionFunction = function (positions) {
  65869. var minlg = pathArray[0].length;
  65870. var i = 0;
  65871. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65872. for (var si = 1; si <= ns; si++) {
  65873. for (var p = 0; p < pathArray.length; p++) {
  65874. var path = pathArray[p];
  65875. var l = path.length;
  65876. minlg = (minlg < l) ? minlg : l;
  65877. var j = 0;
  65878. while (j < minlg) {
  65879. positions[i] = path[j].x;
  65880. positions[i + 1] = path[j].y;
  65881. positions[i + 2] = path[j].z;
  65882. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65883. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65884. }
  65885. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65886. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65887. }
  65888. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65889. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65890. }
  65891. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65892. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65893. }
  65894. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65895. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65896. }
  65897. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65898. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65899. }
  65900. j++;
  65901. i += 3;
  65902. }
  65903. if (instance._closePath) {
  65904. positions[i] = path[0].x;
  65905. positions[i + 1] = path[0].y;
  65906. positions[i + 2] = path[0].z;
  65907. i += 3;
  65908. }
  65909. }
  65910. }
  65911. };
  65912. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65913. positionFunction(positions);
  65914. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65915. instance._boundingInfo.update(instance._worldMatrix);
  65916. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65917. if (options.colors) {
  65918. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65919. for (var c = 0; c < options.colors.length; c++) {
  65920. colors[c * 4] = options.colors[c].r;
  65921. colors[c * 4 + 1] = options.colors[c].g;
  65922. colors[c * 4 + 2] = options.colors[c].b;
  65923. colors[c * 4 + 3] = options.colors[c].a;
  65924. }
  65925. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65926. }
  65927. if (options.uvs) {
  65928. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65929. for (var i = 0; i < options.uvs.length; i++) {
  65930. uvs[i * 2] = options.uvs[i].x;
  65931. uvs[i * 2 + 1] = options.uvs[i].y;
  65932. }
  65933. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65934. }
  65935. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65936. var indices = instance.getIndices();
  65937. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65938. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65939. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65940. if (instance._closePath) {
  65941. var indexFirst = 0;
  65942. var indexLast = 0;
  65943. for (var p = 0; p < pathArray.length; p++) {
  65944. indexFirst = instance._idx[p] * 3;
  65945. if (p + 1 < pathArray.length) {
  65946. indexLast = (instance._idx[p + 1] - 1) * 3;
  65947. }
  65948. else {
  65949. indexLast = normals.length - 3;
  65950. }
  65951. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65952. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65953. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65954. normals[indexLast] = normals[indexFirst];
  65955. normals[indexLast + 1] = normals[indexFirst + 1];
  65956. normals[indexLast + 2] = normals[indexFirst + 2];
  65957. }
  65958. }
  65959. if (!(instance.areNormalsFrozen)) {
  65960. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65961. }
  65962. }
  65963. return instance;
  65964. }
  65965. else { // new ribbon creation
  65966. var ribbon = new BABYLON.Mesh(name, scene);
  65967. ribbon._originalBuilderSideOrientation = sideOrientation;
  65968. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65969. if (closePath) {
  65970. ribbon._idx = vertexData._idx;
  65971. }
  65972. ribbon._closePath = closePath;
  65973. ribbon._closeArray = closeArray;
  65974. vertexData.applyToMesh(ribbon, updatable);
  65975. return ribbon;
  65976. }
  65977. };
  65978. /**
  65979. * Creates a cylinder or a cone mesh
  65980. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  65981. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  65982. * * 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.
  65983. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  65984. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  65985. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  65986. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  65987. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  65988. * * 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).
  65989. * * 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
  65990. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  65991. * * 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
  65992. * * 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.
  65993. * * If `enclose` is false, a ring surface is one element.
  65994. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  65995. * * 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
  65996. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65997. * * 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
  65998. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65999. * @param name defines the name of the mesh
  66000. * @param options defines the options used to create the mesh
  66001. * @param scene defines the hosting scene
  66002. * @returns the cylinder mesh
  66003. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66004. */
  66005. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66006. var cylinder = new BABYLON.Mesh(name, scene);
  66007. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66008. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66009. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66010. vertexData.applyToMesh(cylinder, options.updatable);
  66011. return cylinder;
  66012. };
  66013. /**
  66014. * Creates a torus mesh
  66015. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66016. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66017. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66018. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66019. * * 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
  66020. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66021. * @param name defines the name of the mesh
  66022. * @param options defines the options used to create the mesh
  66023. * @param scene defines the hosting scene
  66024. * @returns the torus mesh
  66025. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66026. */
  66027. MeshBuilder.CreateTorus = function (name, options, scene) {
  66028. var torus = new BABYLON.Mesh(name, scene);
  66029. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66030. torus._originalBuilderSideOrientation = options.sideOrientation;
  66031. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66032. vertexData.applyToMesh(torus, options.updatable);
  66033. return torus;
  66034. };
  66035. /**
  66036. * Creates a torus knot mesh
  66037. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66038. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66039. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66040. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66041. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66042. * * 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
  66043. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66044. * @param name defines the name of the mesh
  66045. * @param options defines the options used to create the mesh
  66046. * @param scene defines the hosting scene
  66047. * @returns the torus knot mesh
  66048. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66049. */
  66050. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66051. var torusKnot = new BABYLON.Mesh(name, scene);
  66052. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66053. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66054. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66055. vertexData.applyToMesh(torusKnot, options.updatable);
  66056. return torusKnot;
  66057. };
  66058. /**
  66059. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66060. * * 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
  66061. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66062. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66063. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66064. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66065. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66066. * * 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
  66067. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66068. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66069. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66070. * @param name defines the name of the new line system
  66071. * @param options defines the options used to create the line system
  66072. * @param scene defines the hosting scene
  66073. * @returns a new line system mesh
  66074. */
  66075. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66076. var instance = options.instance;
  66077. var lines = options.lines;
  66078. var colors = options.colors;
  66079. if (instance) { // lines update
  66080. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66081. var vertexColor;
  66082. var lineColors;
  66083. if (colors) {
  66084. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66085. }
  66086. var i = 0;
  66087. var c = 0;
  66088. for (var l = 0; l < lines.length; l++) {
  66089. var points = lines[l];
  66090. for (var p = 0; p < points.length; p++) {
  66091. positions[i] = points[p].x;
  66092. positions[i + 1] = points[p].y;
  66093. positions[i + 2] = points[p].z;
  66094. if (colors && vertexColor) {
  66095. lineColors = colors[l];
  66096. vertexColor[c] = lineColors[p].r;
  66097. vertexColor[c + 1] = lineColors[p].g;
  66098. vertexColor[c + 2] = lineColors[p].b;
  66099. vertexColor[c + 3] = lineColors[p].a;
  66100. c += 4;
  66101. }
  66102. i += 3;
  66103. }
  66104. }
  66105. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66106. if (colors && vertexColor) {
  66107. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  66108. }
  66109. return instance;
  66110. }
  66111. // line system creation
  66112. var useVertexColor = (colors) ? true : false;
  66113. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  66114. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  66115. vertexData.applyToMesh(lineSystem, options.updatable);
  66116. return lineSystem;
  66117. };
  66118. /**
  66119. * Creates a line mesh
  66120. * 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
  66121. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66122. * * The parameter `points` is an array successive Vector3
  66123. * * 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
  66124. * * The optional parameter `colors` is an array of successive Color4, one per line point
  66125. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  66126. * * When updating an instance, remember that only point positions can change, not the number of points
  66127. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66128. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  66129. * @param name defines the name of the new line system
  66130. * @param options defines the options used to create the line system
  66131. * @param scene defines the hosting scene
  66132. * @returns a new line mesh
  66133. */
  66134. MeshBuilder.CreateLines = function (name, options, scene) {
  66135. if (scene === void 0) { scene = null; }
  66136. var colors = (options.colors) ? [options.colors] : null;
  66137. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  66138. return lines;
  66139. };
  66140. /**
  66141. * Creates a dashed line mesh
  66142. * * 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
  66143. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66144. * * The parameter `points` is an array successive Vector3
  66145. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  66146. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  66147. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  66148. * * 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
  66149. * * When updating an instance, remember that only point positions can change, not the number of points
  66150. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66151. * @param name defines the name of the mesh
  66152. * @param options defines the options used to create the mesh
  66153. * @param scene defines the hosting scene
  66154. * @returns the dashed line mesh
  66155. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  66156. */
  66157. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  66158. if (scene === void 0) { scene = null; }
  66159. var points = options.points;
  66160. var instance = options.instance;
  66161. var gapSize = options.gapSize || 1;
  66162. var dashSize = options.dashSize || 3;
  66163. if (instance) { // dashed lines update
  66164. var positionFunction = function (positions) {
  66165. var curvect = BABYLON.Vector3.Zero();
  66166. var nbSeg = positions.length / 6;
  66167. var lg = 0;
  66168. var nb = 0;
  66169. var shft = 0;
  66170. var dashshft = 0;
  66171. var curshft = 0;
  66172. var p = 0;
  66173. var i = 0;
  66174. var j = 0;
  66175. for (i = 0; i < points.length - 1; i++) {
  66176. points[i + 1].subtractToRef(points[i], curvect);
  66177. lg += curvect.length();
  66178. }
  66179. shft = lg / nbSeg;
  66180. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  66181. for (i = 0; i < points.length - 1; i++) {
  66182. points[i + 1].subtractToRef(points[i], curvect);
  66183. nb = Math.floor(curvect.length() / shft);
  66184. curvect.normalize();
  66185. j = 0;
  66186. while (j < nb && p < positions.length) {
  66187. curshft = shft * j;
  66188. positions[p] = points[i].x + curshft * curvect.x;
  66189. positions[p + 1] = points[i].y + curshft * curvect.y;
  66190. positions[p + 2] = points[i].z + curshft * curvect.z;
  66191. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  66192. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  66193. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  66194. p += 6;
  66195. j++;
  66196. }
  66197. }
  66198. while (p < positions.length) {
  66199. positions[p] = points[i].x;
  66200. positions[p + 1] = points[i].y;
  66201. positions[p + 2] = points[i].z;
  66202. p += 3;
  66203. }
  66204. };
  66205. instance.updateMeshPositions(positionFunction, false);
  66206. return instance;
  66207. }
  66208. // dashed lines creation
  66209. var dashedLines = new BABYLON.LinesMesh(name, scene);
  66210. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  66211. vertexData.applyToMesh(dashedLines, options.updatable);
  66212. dashedLines.dashSize = dashSize;
  66213. dashedLines.gapSize = gapSize;
  66214. return dashedLines;
  66215. };
  66216. /**
  66217. * 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.
  66218. * * 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.
  66219. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66220. * * 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.
  66221. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  66222. * * 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
  66223. * * 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
  66224. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  66225. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66226. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  66227. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  66228. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66229. * @param name defines the name of the mesh
  66230. * @param options defines the options used to create the mesh
  66231. * @param scene defines the hosting scene
  66232. * @returns the extruded shape mesh
  66233. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66234. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66235. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66236. */
  66237. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  66238. if (scene === void 0) { scene = null; }
  66239. var path = options.path;
  66240. var shape = options.shape;
  66241. var scale = options.scale || 1;
  66242. var rotation = options.rotation || 0;
  66243. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66244. var updatable = options.updatable;
  66245. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66246. var instance = options.instance || null;
  66247. var invertUV = options.invertUV || false;
  66248. 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);
  66249. };
  66250. /**
  66251. * Creates an custom extruded shape mesh.
  66252. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  66253. * * 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.
  66254. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66255. * * 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
  66256. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  66257. * * 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
  66258. * * It must returns a float value that will be the scale value applied to the shape on each path point
  66259. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  66260. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  66261. * * 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
  66262. * * 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
  66263. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  66264. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66265. * * 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
  66266. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66267. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66268. * @param name defines the name of the mesh
  66269. * @param options defines the options used to create the mesh
  66270. * @param scene defines the hosting scene
  66271. * @returns the custom extruded shape mesh
  66272. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  66273. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66274. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66275. */
  66276. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  66277. var path = options.path;
  66278. var shape = options.shape;
  66279. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66280. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66281. var ribbonCloseArray = options.ribbonCloseArray || false;
  66282. var ribbonClosePath = options.ribbonClosePath || false;
  66283. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66284. var updatable = options.updatable;
  66285. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66286. var instance = options.instance;
  66287. var invertUV = options.invertUV || false;
  66288. 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);
  66289. };
  66290. /**
  66291. * Creates lathe mesh.
  66292. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66293. * * 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
  66294. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66295. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66296. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66297. * * 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
  66298. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66299. * * 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
  66300. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66301. * * 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
  66302. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66303. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66304. * @param name defines the name of the mesh
  66305. * @param options defines the options used to create the mesh
  66306. * @param scene defines the hosting scene
  66307. * @returns the lathe mesh
  66308. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66309. */
  66310. MeshBuilder.CreateLathe = function (name, options, scene) {
  66311. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66312. var closed = (options.closed === undefined) ? true : options.closed;
  66313. var shape = options.shape;
  66314. var radius = options.radius || 1;
  66315. var tessellation = options.tessellation || 64;
  66316. var clip = options.clip || 0;
  66317. var updatable = options.updatable;
  66318. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66319. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66320. var pi2 = Math.PI * 2;
  66321. var paths = new Array();
  66322. var invertUV = options.invertUV || false;
  66323. var i = 0;
  66324. var p = 0;
  66325. var step = pi2 / tessellation * arc;
  66326. var rotated;
  66327. var path = new Array();
  66328. for (i = 0; i <= tessellation - clip; i++) {
  66329. var path = [];
  66330. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66331. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66332. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66333. }
  66334. for (p = 0; p < shape.length; p++) {
  66335. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66336. path.push(rotated);
  66337. }
  66338. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66339. 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));
  66340. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66341. }
  66342. paths.push(path);
  66343. }
  66344. // lathe ribbon
  66345. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66346. return lathe;
  66347. };
  66348. /**
  66349. * Creates a plane mesh
  66350. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66351. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66352. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66353. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66354. * * 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
  66355. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66356. * @param name defines the name of the mesh
  66357. * @param options defines the options used to create the mesh
  66358. * @param scene defines the hosting scene
  66359. * @returns the plane mesh
  66360. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66361. */
  66362. MeshBuilder.CreatePlane = function (name, options, scene) {
  66363. var plane = new BABYLON.Mesh(name, scene);
  66364. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66365. plane._originalBuilderSideOrientation = options.sideOrientation;
  66366. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66367. vertexData.applyToMesh(plane, options.updatable);
  66368. if (options.sourcePlane) {
  66369. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66370. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66371. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66372. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66373. plane.rotate(vectorProduct, product);
  66374. }
  66375. }
  66376. return plane;
  66377. };
  66378. /**
  66379. * Creates a ground mesh
  66380. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66381. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66382. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66383. * @param name defines the name of the mesh
  66384. * @param options defines the options used to create the mesh
  66385. * @param scene defines the hosting scene
  66386. * @returns the ground mesh
  66387. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66388. */
  66389. MeshBuilder.CreateGround = function (name, options, scene) {
  66390. var ground = new BABYLON.GroundMesh(name, scene);
  66391. ground._setReady(false);
  66392. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66393. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66394. ground._width = options.width || 1;
  66395. ground._height = options.height || 1;
  66396. ground._maxX = ground._width / 2;
  66397. ground._maxZ = ground._height / 2;
  66398. ground._minX = -ground._maxX;
  66399. ground._minZ = -ground._maxZ;
  66400. var vertexData = BABYLON.VertexData.CreateGround(options);
  66401. vertexData.applyToMesh(ground, options.updatable);
  66402. ground._setReady(true);
  66403. return ground;
  66404. };
  66405. /**
  66406. * Creates a tiled ground mesh
  66407. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66408. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66409. * * 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
  66410. * * 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
  66411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66412. * @param name defines the name of the mesh
  66413. * @param options defines the options used to create the mesh
  66414. * @param scene defines the hosting scene
  66415. * @returns the tiled ground mesh
  66416. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66417. */
  66418. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66419. var tiledGround = new BABYLON.Mesh(name, scene);
  66420. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66421. vertexData.applyToMesh(tiledGround, options.updatable);
  66422. return tiledGround;
  66423. };
  66424. /**
  66425. * Creates a ground mesh from a height map
  66426. * * The parameter `url` sets the URL of the height map image resource.
  66427. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66428. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66429. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66430. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66431. * * 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.
  66432. * * 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).
  66433. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66434. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66435. * @param name defines the name of the mesh
  66436. * @param url defines the url to the height map
  66437. * @param options defines the options used to create the mesh
  66438. * @param scene defines the hosting scene
  66439. * @returns the ground mesh
  66440. * @see http://doc.babylonjs.com/babylon101/height_map
  66441. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66442. */
  66443. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66444. var width = options.width || 10.0;
  66445. var height = options.height || 10.0;
  66446. var subdivisions = options.subdivisions || 1 | 0;
  66447. var minHeight = options.minHeight || 0.0;
  66448. var maxHeight = options.maxHeight || 1.0;
  66449. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66450. var alphaFilter = options.alphaFilter || 0.0;
  66451. var updatable = options.updatable;
  66452. var onReady = options.onReady;
  66453. var ground = new BABYLON.GroundMesh(name, scene);
  66454. ground._subdivisionsX = subdivisions;
  66455. ground._subdivisionsY = subdivisions;
  66456. ground._width = width;
  66457. ground._height = height;
  66458. ground._maxX = ground._width / 2.0;
  66459. ground._maxZ = ground._height / 2.0;
  66460. ground._minX = -ground._maxX;
  66461. ground._minZ = -ground._maxZ;
  66462. ground._setReady(false);
  66463. var onload = function (img) {
  66464. // Getting height map data
  66465. var canvas = document.createElement("canvas");
  66466. var context = canvas.getContext("2d");
  66467. if (!context) {
  66468. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66469. }
  66470. if (scene.isDisposed) {
  66471. return;
  66472. }
  66473. var bufferWidth = img.width;
  66474. var bufferHeight = img.height;
  66475. canvas.width = bufferWidth;
  66476. canvas.height = bufferHeight;
  66477. context.drawImage(img, 0, 0);
  66478. // Create VertexData from map data
  66479. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66480. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66481. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66482. width: width, height: height,
  66483. subdivisions: subdivisions,
  66484. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66485. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66486. alphaFilter: alphaFilter
  66487. });
  66488. vertexData.applyToMesh(ground, updatable);
  66489. //execute ready callback, if set
  66490. if (onReady) {
  66491. onReady(ground);
  66492. }
  66493. ground._setReady(true);
  66494. };
  66495. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66496. return ground;
  66497. };
  66498. /**
  66499. * Creates a polygon mesh
  66500. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66501. * * 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
  66502. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66503. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66504. * * 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)
  66505. * * Remember you can only change the shape positions, not their number when updating a polygon
  66506. * @param name defines the name of the mesh
  66507. * @param options defines the options used to create the mesh
  66508. * @param scene defines the hosting scene
  66509. * @returns the polygon mesh
  66510. */
  66511. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66512. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66513. var shape = options.shape;
  66514. var holes = options.holes || [];
  66515. var depth = options.depth || 0;
  66516. var contours = [];
  66517. var hole = [];
  66518. for (var i = 0; i < shape.length; i++) {
  66519. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66520. }
  66521. var epsilon = 0.00000001;
  66522. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66523. contours.pop();
  66524. }
  66525. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66526. for (var hNb = 0; hNb < holes.length; hNb++) {
  66527. hole = [];
  66528. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66529. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66530. }
  66531. polygonTriangulation.addHole(hole);
  66532. }
  66533. var polygon = polygonTriangulation.build(options.updatable, depth);
  66534. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66535. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66536. vertexData.applyToMesh(polygon, options.updatable);
  66537. return polygon;
  66538. };
  66539. ;
  66540. /**
  66541. * Creates an extruded polygon mesh, with depth in the Y direction.
  66542. * * 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)
  66543. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66544. * @param name defines the name of the mesh
  66545. * @param options defines the options used to create the mesh
  66546. * @param scene defines the hosting scene
  66547. * @returns the polygon mesh
  66548. */
  66549. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66550. return MeshBuilder.CreatePolygon(name, options, scene);
  66551. };
  66552. ;
  66553. /**
  66554. * Creates a tube mesh.
  66555. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66556. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66557. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66558. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66559. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66560. * * 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)
  66561. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66562. * * 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
  66563. * * 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
  66564. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66565. * * 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
  66566. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66567. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66568. * @param name defines the name of the mesh
  66569. * @param options defines the options used to create the mesh
  66570. * @param scene defines the hosting scene
  66571. * @returns the tube mesh
  66572. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66573. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66574. */
  66575. MeshBuilder.CreateTube = function (name, options, scene) {
  66576. var path = options.path;
  66577. var instance = options.instance;
  66578. var radius = 1.0;
  66579. if (instance) {
  66580. radius = instance.radius;
  66581. }
  66582. if (options.radius !== undefined) {
  66583. radius = options.radius;
  66584. }
  66585. ;
  66586. var tessellation = options.tessellation || 64 | 0;
  66587. var radiusFunction = options.radiusFunction || null;
  66588. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66589. var invertUV = options.invertUV || false;
  66590. var updatable = options.updatable;
  66591. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66592. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66593. // tube geometry
  66594. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66595. var tangents = path3D.getTangents();
  66596. var normals = path3D.getNormals();
  66597. var distances = path3D.getDistances();
  66598. var pi2 = Math.PI * 2;
  66599. var step = pi2 / tessellation * arc;
  66600. var returnRadius = function () { return radius; };
  66601. var radiusFunctionFinal = radiusFunction || returnRadius;
  66602. var circlePath;
  66603. var rad;
  66604. var normal;
  66605. var rotated;
  66606. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66607. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66608. for (var i = 0; i < path.length; i++) {
  66609. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66610. circlePath = Array(); // current circle array
  66611. normal = normals[i]; // current normal
  66612. for (var t = 0; t < tessellation; t++) {
  66613. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66614. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66615. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66616. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66617. circlePath[t] = rotated;
  66618. }
  66619. circlePaths[index] = circlePath;
  66620. index++;
  66621. }
  66622. // cap
  66623. var capPath = function (nbPoints, pathIndex) {
  66624. var pointCap = Array();
  66625. for (var i = 0; i < nbPoints; i++) {
  66626. pointCap.push(path[pathIndex]);
  66627. }
  66628. return pointCap;
  66629. };
  66630. switch (cap) {
  66631. case BABYLON.Mesh.NO_CAP:
  66632. break;
  66633. case BABYLON.Mesh.CAP_START:
  66634. circlePaths[0] = capPath(tessellation, 0);
  66635. circlePaths[1] = circlePaths[2].slice(0);
  66636. break;
  66637. case BABYLON.Mesh.CAP_END:
  66638. circlePaths[index] = circlePaths[index - 1].slice(0);
  66639. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66640. break;
  66641. case BABYLON.Mesh.CAP_ALL:
  66642. circlePaths[0] = capPath(tessellation, 0);
  66643. circlePaths[1] = circlePaths[2].slice(0);
  66644. circlePaths[index] = circlePaths[index - 1].slice(0);
  66645. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66646. break;
  66647. default:
  66648. break;
  66649. }
  66650. return circlePaths;
  66651. };
  66652. var path3D;
  66653. var pathArray;
  66654. if (instance) { // tube update
  66655. var arc = options.arc || instance.arc;
  66656. path3D = (instance.path3D).update(path);
  66657. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66658. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66659. instance.path3D = path3D;
  66660. instance.pathArray = pathArray;
  66661. instance.arc = arc;
  66662. instance.radius = radius;
  66663. return instance;
  66664. }
  66665. // tube creation
  66666. path3D = new BABYLON.Path3D(path);
  66667. var newPathArray = new Array();
  66668. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66669. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66670. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66671. tube.pathArray = pathArray;
  66672. tube.path3D = path3D;
  66673. tube.tessellation = tessellation;
  66674. tube.cap = cap;
  66675. tube.arc = options.arc;
  66676. tube.radius = radius;
  66677. return tube;
  66678. };
  66679. /**
  66680. * Creates a polyhedron mesh
  66681. * * 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
  66682. * * The parameter `size` (positive float, default 1) sets the polygon size
  66683. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66684. * * 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`
  66685. * * 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
  66686. * * 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)`)
  66687. * * 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
  66688. * * 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
  66689. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66690. * * 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
  66691. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66692. * @param name defines the name of the mesh
  66693. * @param options defines the options used to create the mesh
  66694. * @param scene defines the hosting scene
  66695. * @returns the polyhedron mesh
  66696. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66697. */
  66698. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66699. var polyhedron = new BABYLON.Mesh(name, scene);
  66700. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66701. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66702. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66703. vertexData.applyToMesh(polyhedron, options.updatable);
  66704. return polyhedron;
  66705. };
  66706. /**
  66707. * Creates a decal mesh.
  66708. * 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
  66709. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66710. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66711. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66712. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66713. * @param name defines the name of the mesh
  66714. * @param sourceMesh defines the mesh where the decal must be applied
  66715. * @param options defines the options used to create the mesh
  66716. * @param scene defines the hosting scene
  66717. * @returns the decal mesh
  66718. * @see http://doc.babylonjs.com/how_to/decals
  66719. */
  66720. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66721. var indices = sourceMesh.getIndices();
  66722. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66723. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66724. var position = options.position || BABYLON.Vector3.Zero();
  66725. var normal = options.normal || BABYLON.Vector3.Up();
  66726. var size = options.size || BABYLON.Vector3.One();
  66727. var angle = options.angle || 0;
  66728. // Getting correct rotation
  66729. if (!normal) {
  66730. var target = new BABYLON.Vector3(0, 0, 1);
  66731. var camera = sourceMesh.getScene().activeCamera;
  66732. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66733. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66734. }
  66735. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66736. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66737. var pitch = Math.atan2(normal.y, len);
  66738. // Matrix
  66739. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66740. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66741. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66742. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66743. var vertexData = new BABYLON.VertexData();
  66744. vertexData.indices = [];
  66745. vertexData.positions = [];
  66746. vertexData.normals = [];
  66747. vertexData.uvs = [];
  66748. var currentVertexDataIndex = 0;
  66749. var extractDecalVector3 = function (indexId) {
  66750. var result = new BABYLON.PositionNormalVertex();
  66751. if (!indices || !positions || !normals) {
  66752. return result;
  66753. }
  66754. var vertexId = indices[indexId];
  66755. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66756. // Send vector to decal local world
  66757. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66758. // Get normal
  66759. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66760. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66761. return result;
  66762. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66763. var clip = function (vertices, axis) {
  66764. if (vertices.length === 0) {
  66765. return vertices;
  66766. }
  66767. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66768. var clipVertices = function (v0, v1) {
  66769. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66770. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66771. };
  66772. var result = new Array();
  66773. for (var index = 0; index < vertices.length; index += 3) {
  66774. var v1Out;
  66775. var v2Out;
  66776. var v3Out;
  66777. var total = 0;
  66778. var nV1 = null;
  66779. var nV2 = null;
  66780. var nV3 = null;
  66781. var nV4 = null;
  66782. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66783. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66784. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66785. v1Out = d1 > 0;
  66786. v2Out = d2 > 0;
  66787. v3Out = d3 > 0;
  66788. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66789. switch (total) {
  66790. case 0:
  66791. result.push(vertices[index]);
  66792. result.push(vertices[index + 1]);
  66793. result.push(vertices[index + 2]);
  66794. break;
  66795. case 1:
  66796. if (v1Out) {
  66797. nV1 = vertices[index + 1];
  66798. nV2 = vertices[index + 2];
  66799. nV3 = clipVertices(vertices[index], nV1);
  66800. nV4 = clipVertices(vertices[index], nV2);
  66801. }
  66802. if (v2Out) {
  66803. nV1 = vertices[index];
  66804. nV2 = vertices[index + 2];
  66805. nV3 = clipVertices(vertices[index + 1], nV1);
  66806. nV4 = clipVertices(vertices[index + 1], nV2);
  66807. result.push(nV3);
  66808. result.push(nV2.clone());
  66809. result.push(nV1.clone());
  66810. result.push(nV2.clone());
  66811. result.push(nV3.clone());
  66812. result.push(nV4);
  66813. break;
  66814. }
  66815. if (v3Out) {
  66816. nV1 = vertices[index];
  66817. nV2 = vertices[index + 1];
  66818. nV3 = clipVertices(vertices[index + 2], nV1);
  66819. nV4 = clipVertices(vertices[index + 2], nV2);
  66820. }
  66821. if (nV1 && nV2 && nV3 && nV4) {
  66822. result.push(nV1.clone());
  66823. result.push(nV2.clone());
  66824. result.push(nV3);
  66825. result.push(nV4);
  66826. result.push(nV3.clone());
  66827. result.push(nV2.clone());
  66828. }
  66829. break;
  66830. case 2:
  66831. if (!v1Out) {
  66832. nV1 = vertices[index].clone();
  66833. nV2 = clipVertices(nV1, vertices[index + 1]);
  66834. nV3 = clipVertices(nV1, vertices[index + 2]);
  66835. result.push(nV1);
  66836. result.push(nV2);
  66837. result.push(nV3);
  66838. }
  66839. if (!v2Out) {
  66840. nV1 = vertices[index + 1].clone();
  66841. nV2 = clipVertices(nV1, vertices[index + 2]);
  66842. nV3 = clipVertices(nV1, vertices[index]);
  66843. result.push(nV1);
  66844. result.push(nV2);
  66845. result.push(nV3);
  66846. }
  66847. if (!v3Out) {
  66848. nV1 = vertices[index + 2].clone();
  66849. nV2 = clipVertices(nV1, vertices[index]);
  66850. nV3 = clipVertices(nV1, vertices[index + 1]);
  66851. result.push(nV1);
  66852. result.push(nV2);
  66853. result.push(nV3);
  66854. }
  66855. break;
  66856. case 3:
  66857. break;
  66858. }
  66859. }
  66860. return result;
  66861. };
  66862. for (var index = 0; index < indices.length; index += 3) {
  66863. var faceVertices = new Array();
  66864. faceVertices.push(extractDecalVector3(index));
  66865. faceVertices.push(extractDecalVector3(index + 1));
  66866. faceVertices.push(extractDecalVector3(index + 2));
  66867. // Clip
  66868. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66869. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66870. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66871. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66872. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66873. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66874. if (faceVertices.length === 0) {
  66875. continue;
  66876. }
  66877. // Add UVs and get back to world
  66878. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66879. var vertex = faceVertices[vIndex];
  66880. //TODO check for Int32Array | Uint32Array | Uint16Array
  66881. vertexData.indices.push(currentVertexDataIndex);
  66882. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66883. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66884. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66885. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66886. currentVertexDataIndex++;
  66887. }
  66888. }
  66889. // Return mesh
  66890. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66891. vertexData.applyToMesh(decal);
  66892. decal.position = position.clone();
  66893. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66894. return decal;
  66895. };
  66896. // Privates
  66897. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66898. // extrusion geometry
  66899. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66900. var tangents = path3D.getTangents();
  66901. var normals = path3D.getNormals();
  66902. var binormals = path3D.getBinormals();
  66903. var distances = path3D.getDistances();
  66904. var angle = 0;
  66905. var returnScale = function () { return scale !== null ? scale : 1; };
  66906. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66907. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66908. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66909. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66910. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66911. for (var i = 0; i < curve.length; i++) {
  66912. var shapePath = new Array();
  66913. var angleStep = rotate(i, distances[i]);
  66914. var scaleRatio = scl(i, distances[i]);
  66915. for (var p = 0; p < shape.length; p++) {
  66916. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66917. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66918. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66919. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66920. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66921. shapePath[p] = rotated;
  66922. }
  66923. shapePaths[index] = shapePath;
  66924. angle += angleStep;
  66925. index++;
  66926. }
  66927. // cap
  66928. var capPath = function (shapePath) {
  66929. var pointCap = Array();
  66930. var barycenter = BABYLON.Vector3.Zero();
  66931. var i;
  66932. for (i = 0; i < shapePath.length; i++) {
  66933. barycenter.addInPlace(shapePath[i]);
  66934. }
  66935. barycenter.scaleInPlace(1.0 / shapePath.length);
  66936. for (i = 0; i < shapePath.length; i++) {
  66937. pointCap.push(barycenter);
  66938. }
  66939. return pointCap;
  66940. };
  66941. switch (cap) {
  66942. case BABYLON.Mesh.NO_CAP:
  66943. break;
  66944. case BABYLON.Mesh.CAP_START:
  66945. shapePaths[0] = capPath(shapePaths[2]);
  66946. shapePaths[1] = shapePaths[2];
  66947. break;
  66948. case BABYLON.Mesh.CAP_END:
  66949. shapePaths[index] = shapePaths[index - 1];
  66950. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66951. break;
  66952. case BABYLON.Mesh.CAP_ALL:
  66953. shapePaths[0] = capPath(shapePaths[2]);
  66954. shapePaths[1] = shapePaths[2];
  66955. shapePaths[index] = shapePaths[index - 1];
  66956. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66957. break;
  66958. default:
  66959. break;
  66960. }
  66961. return shapePaths;
  66962. };
  66963. var path3D;
  66964. var pathArray;
  66965. if (instance) { // instance update
  66966. path3D = (instance.path3D).update(curve);
  66967. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66968. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66969. return instance;
  66970. }
  66971. // extruded shape creation
  66972. path3D = new BABYLON.Path3D(curve);
  66973. var newShapePaths = new Array();
  66974. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66975. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  66976. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  66977. extrudedGeneric.pathArray = pathArray;
  66978. extrudedGeneric.path3D = path3D;
  66979. extrudedGeneric.cap = cap;
  66980. return extrudedGeneric;
  66981. };
  66982. return MeshBuilder;
  66983. }());
  66984. BABYLON.MeshBuilder = MeshBuilder;
  66985. })(BABYLON || (BABYLON = {}));
  66986. //# sourceMappingURL=babylon.meshBuilder.js.map
  66987. var BABYLON;
  66988. (function (BABYLON) {
  66989. /**
  66990. * Draco compression (https://google.github.io/draco/)
  66991. *
  66992. * This class wraps the Draco module.
  66993. *
  66994. * **Encoder**
  66995. *
  66996. * The encoder is not currently implemented.
  66997. *
  66998. * **Decoder**
  66999. *
  67000. * 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.
  67001. *
  67002. * To update the configuration, use the following code:
  67003. * ```javascript
  67004. * BABYLON.DracoCompression.Configuration = {
  67005. * decoder: {
  67006. * wasmUrl: "<url to the WebAssembly library>",
  67007. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67008. * fallbackUrl: "<url to the fallback JavaScript library>",
  67009. * }
  67010. * };
  67011. * ```
  67012. *
  67013. * 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.
  67014. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67015. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67016. *
  67017. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67018. * ```javascript
  67019. * var dracoCompression = new BABYLON.DracoCompression();
  67020. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67021. * [BABYLON.VertexBuffer.PositionKind]: 0
  67022. * });
  67023. * ```
  67024. *
  67025. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67026. */
  67027. var DracoCompression = /** @class */ (function () {
  67028. /**
  67029. * Constructor
  67030. */
  67031. function DracoCompression() {
  67032. }
  67033. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67034. /**
  67035. * Returns true if the decoder is available.
  67036. */
  67037. get: function () {
  67038. if (typeof DracoDecoderModule !== "undefined") {
  67039. return true;
  67040. }
  67041. var decoder = DracoCompression.Configuration.decoder;
  67042. if (decoder) {
  67043. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67044. return true;
  67045. }
  67046. if (decoder.fallbackUrl) {
  67047. return true;
  67048. }
  67049. }
  67050. return false;
  67051. },
  67052. enumerable: true,
  67053. configurable: true
  67054. });
  67055. /**
  67056. * Stop all async operations and release resources.
  67057. */
  67058. DracoCompression.prototype.dispose = function () {
  67059. };
  67060. /**
  67061. * Decode Draco compressed mesh data to vertex data.
  67062. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67063. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67064. * @returns A promise that resolves with the decoded vertex data
  67065. */
  67066. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67067. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67068. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67069. var module = wrappedModule.module;
  67070. var vertexData = new BABYLON.VertexData();
  67071. var buffer = new module.DecoderBuffer();
  67072. buffer.Init(dataView, dataView.byteLength);
  67073. var decoder = new module.Decoder();
  67074. var geometry;
  67075. var status;
  67076. try {
  67077. var type = decoder.GetEncodedGeometryType(buffer);
  67078. switch (type) {
  67079. case module.TRIANGULAR_MESH:
  67080. geometry = new module.Mesh();
  67081. status = decoder.DecodeBufferToMesh(buffer, geometry);
  67082. break;
  67083. case module.POINT_CLOUD:
  67084. geometry = new module.PointCloud();
  67085. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  67086. break;
  67087. default:
  67088. throw new Error("Invalid geometry type " + type);
  67089. }
  67090. if (!status.ok() || !geometry.ptr) {
  67091. throw new Error(status.error_msg());
  67092. }
  67093. var numPoints = geometry.num_points();
  67094. if (type === module.TRIANGULAR_MESH) {
  67095. var numFaces = geometry.num_faces();
  67096. var faceIndices = new module.DracoInt32Array();
  67097. try {
  67098. var indices = new Uint32Array(numFaces * 3);
  67099. for (var i = 0; i < numFaces; i++) {
  67100. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  67101. var offset = i * 3;
  67102. indices[offset + 0] = faceIndices.GetValue(0);
  67103. indices[offset + 1] = faceIndices.GetValue(1);
  67104. indices[offset + 2] = faceIndices.GetValue(2);
  67105. }
  67106. vertexData.indices = indices;
  67107. }
  67108. finally {
  67109. module.destroy(faceIndices);
  67110. }
  67111. }
  67112. for (var kind in attributes) {
  67113. var uniqueId = attributes[kind];
  67114. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  67115. var dracoData = new module.DracoFloat32Array();
  67116. try {
  67117. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  67118. var babylonData = new Float32Array(numPoints * attribute.num_components());
  67119. for (var i = 0; i < babylonData.length; i++) {
  67120. babylonData[i] = dracoData.GetValue(i);
  67121. }
  67122. vertexData.set(babylonData, kind);
  67123. }
  67124. finally {
  67125. module.destroy(dracoData);
  67126. }
  67127. }
  67128. }
  67129. finally {
  67130. if (geometry) {
  67131. module.destroy(geometry);
  67132. }
  67133. module.destroy(decoder);
  67134. module.destroy(buffer);
  67135. }
  67136. return vertexData;
  67137. });
  67138. };
  67139. DracoCompression._GetDecoderModule = function () {
  67140. if (!DracoCompression._DecoderModulePromise) {
  67141. var promise = null;
  67142. var config_1 = {};
  67143. if (typeof DracoDecoderModule !== "undefined") {
  67144. promise = Promise.resolve();
  67145. }
  67146. else {
  67147. var decoder = DracoCompression.Configuration.decoder;
  67148. if (decoder) {
  67149. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67150. promise = Promise.all([
  67151. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  67152. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  67153. config_1.wasmBinary = data;
  67154. })
  67155. ]);
  67156. }
  67157. else if (decoder.fallbackUrl) {
  67158. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  67159. }
  67160. }
  67161. }
  67162. if (!promise) {
  67163. throw new Error("Draco decoder module is not available");
  67164. }
  67165. DracoCompression._DecoderModulePromise = promise.then(function () {
  67166. return new Promise(function (resolve) {
  67167. config_1.onModuleLoaded = function (decoderModule) {
  67168. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  67169. resolve({ module: decoderModule });
  67170. };
  67171. DracoDecoderModule(config_1);
  67172. });
  67173. });
  67174. }
  67175. return DracoCompression._DecoderModulePromise;
  67176. };
  67177. DracoCompression._LoadScriptAsync = function (url) {
  67178. return new Promise(function (resolve, reject) {
  67179. BABYLON.Tools.LoadScript(url, function () {
  67180. resolve();
  67181. }, function (message) {
  67182. reject(new Error(message));
  67183. });
  67184. });
  67185. };
  67186. DracoCompression._LoadFileAsync = function (url) {
  67187. return new Promise(function (resolve, reject) {
  67188. BABYLON.Tools.LoadFile(url, function (data) {
  67189. resolve(data);
  67190. }, undefined, undefined, true, function (request, exception) {
  67191. reject(exception);
  67192. });
  67193. });
  67194. };
  67195. /**
  67196. * The configuration. Defaults to the following urls:
  67197. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  67198. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  67199. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67200. */
  67201. DracoCompression.Configuration = {
  67202. decoder: {
  67203. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  67204. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  67205. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67206. }
  67207. };
  67208. return DracoCompression;
  67209. }());
  67210. BABYLON.DracoCompression = DracoCompression;
  67211. })(BABYLON || (BABYLON = {}));
  67212. //# sourceMappingURL=babylon.dracoCompression.js.map
  67213. var BABYLON;
  67214. (function (BABYLON) {
  67215. // Sets the default audio engine to Babylon JS.
  67216. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  67217. /**
  67218. * This represents the default audio engine used in babylon.
  67219. * It is responsible to play, synchronize and analyse sounds throughout the application.
  67220. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67221. */
  67222. var AudioEngine = /** @class */ (function () {
  67223. /**
  67224. * Instantiates a new audio engine.
  67225. *
  67226. * There should be only one per page as some browsers restrict the number
  67227. * of audio contexts you can create.
  67228. * @param engine defines the hosting engine
  67229. */
  67230. function AudioEngine(engine) {
  67231. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  67232. var _this = this;
  67233. this._audioContext = null;
  67234. this._audioContextInitialized = false;
  67235. this._muteButton = null;
  67236. /**
  67237. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  67238. */
  67239. this.canUseWebAudio = false;
  67240. /**
  67241. * Defines if Babylon should emit a warning if WebAudio is not supported.
  67242. * @ignoreNaming
  67243. */
  67244. this.WarnedWebAudioUnsupported = false;
  67245. /**
  67246. * Gets whether or not mp3 are supported by your browser.
  67247. */
  67248. this.isMP3supported = false;
  67249. /**
  67250. * Gets whether or not ogg are supported by your browser.
  67251. */
  67252. this.isOGGsupported = false;
  67253. /**
  67254. * Gets whether audio has been unlocked on the device.
  67255. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  67256. * a user interaction has happened.
  67257. */
  67258. this.unlocked = true;
  67259. /**
  67260. * Defines if the audio engine relies on a custom unlocked button.
  67261. * In this case, the embedded button will not be displayed.
  67262. */
  67263. this.useCustomUnlockedButton = false;
  67264. /**
  67265. * Event raised when audio has been unlocked on the browser.
  67266. */
  67267. this.onAudioUnlockedObservable = new BABYLON.Observable();
  67268. /**
  67269. * Event raised when audio has been locked on the browser.
  67270. */
  67271. this.onAudioLockedObservable = new BABYLON.Observable();
  67272. this._tryToRun = false;
  67273. this._onResize = function () {
  67274. _this._moveButtonToTopLeft();
  67275. };
  67276. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  67277. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  67278. this.canUseWebAudio = true;
  67279. }
  67280. var audioElem = document.createElement('audio');
  67281. this._engine = engine;
  67282. try {
  67283. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67284. this.isMP3supported = true;
  67285. }
  67286. }
  67287. catch (e) {
  67288. // protect error during capability check.
  67289. }
  67290. try {
  67291. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67292. this.isOGGsupported = true;
  67293. }
  67294. }
  67295. catch (e) {
  67296. // protect error during capability check.
  67297. }
  67298. }
  67299. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67300. /**
  67301. * Gets the current AudioContext if available.
  67302. */
  67303. get: function () {
  67304. if (!this._audioContextInitialized) {
  67305. this._initializeAudioContext();
  67306. }
  67307. else {
  67308. if (!this.unlocked && !this._muteButton) {
  67309. this._displayMuteButton();
  67310. }
  67311. }
  67312. return this._audioContext;
  67313. },
  67314. enumerable: true,
  67315. configurable: true
  67316. });
  67317. /**
  67318. * Flags the audio engine in Locked state.
  67319. * This happens due to new browser policies preventing audio to autoplay.
  67320. */
  67321. AudioEngine.prototype.lock = function () {
  67322. this._triggerSuspendedState();
  67323. };
  67324. /**
  67325. * Unlocks the audio engine once a user action has been done on the dom.
  67326. * This is helpful to resume play once browser policies have been satisfied.
  67327. */
  67328. AudioEngine.prototype.unlock = function () {
  67329. this._triggerRunningState();
  67330. };
  67331. AudioEngine.prototype._resumeAudioContext = function () {
  67332. var result;
  67333. if (this._audioContext.resume) {
  67334. result = this._audioContext.resume();
  67335. }
  67336. return result || Promise.resolve();
  67337. };
  67338. AudioEngine.prototype._initializeAudioContext = function () {
  67339. var _this = this;
  67340. try {
  67341. if (this.canUseWebAudio) {
  67342. this._audioContext = new AudioContext();
  67343. // create a global volume gain node
  67344. this.masterGain = this._audioContext.createGain();
  67345. this.masterGain.gain.value = 1;
  67346. this.masterGain.connect(this._audioContext.destination);
  67347. this._audioContextInitialized = true;
  67348. if (this._audioContext.state === "running") {
  67349. // Do not wait for the promise to unlock.
  67350. this._triggerRunningState();
  67351. }
  67352. else {
  67353. if (this._audioContext && this._audioContext.resume) {
  67354. this._resumeAudioContext().then(function () {
  67355. _this._triggerRunningState();
  67356. }).catch(function () {
  67357. // Can not resume automatically
  67358. // Needs user action
  67359. _this.lock();
  67360. });
  67361. }
  67362. }
  67363. }
  67364. }
  67365. catch (e) {
  67366. this.canUseWebAudio = false;
  67367. BABYLON.Tools.Error("Web Audio: " + e.message);
  67368. }
  67369. };
  67370. AudioEngine.prototype._triggerRunningState = function () {
  67371. var _this = this;
  67372. if (this._tryToRun) {
  67373. return;
  67374. }
  67375. this._tryToRun = true;
  67376. this._resumeAudioContext()
  67377. .then(function () {
  67378. _this._tryToRun = false;
  67379. _this.unlocked = true;
  67380. if (_this._muteButton) {
  67381. _this._hideMuteButton();
  67382. }
  67383. // Notify users that the audio stack is unlocked/unmuted
  67384. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67385. }).catch(function () {
  67386. _this._tryToRun = false;
  67387. _this.unlocked = false;
  67388. });
  67389. };
  67390. AudioEngine.prototype._triggerSuspendedState = function () {
  67391. this.unlocked = false;
  67392. this.onAudioLockedObservable.notifyObservers(this);
  67393. this._displayMuteButton();
  67394. };
  67395. AudioEngine.prototype._displayMuteButton = function () {
  67396. var _this = this;
  67397. if (this.useCustomUnlockedButton) {
  67398. return;
  67399. }
  67400. this._canvas = this._engine.getRenderingCanvas();
  67401. this._muteButton = document.createElement("BUTTON");
  67402. this._muteButton.className = "babylonUnmuteIcon";
  67403. this._muteButton.id = "babylonUnmuteIconBtn";
  67404. this._muteButton.title = "Unmute";
  67405. 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) }";
  67406. var style = document.createElement('style');
  67407. style.appendChild(document.createTextNode(css));
  67408. document.getElementsByTagName('head')[0].appendChild(style);
  67409. document.body.appendChild(this._muteButton);
  67410. this._moveButtonToTopLeft();
  67411. this._muteButton.addEventListener('mousedown', function () {
  67412. _this._triggerRunningState();
  67413. }, true);
  67414. this._muteButton.addEventListener('touchend', function () {
  67415. _this._triggerRunningState();
  67416. }, true);
  67417. this._muteButton.addEventListener('click', function () {
  67418. _this._triggerRunningState();
  67419. }, true);
  67420. window.addEventListener("resize", this._onResize);
  67421. };
  67422. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67423. if (this._canvas && this._muteButton) {
  67424. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67425. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67426. }
  67427. };
  67428. AudioEngine.prototype._hideMuteButton = function () {
  67429. if (this._muteButton) {
  67430. document.body.removeChild(this._muteButton);
  67431. this._muteButton = null;
  67432. }
  67433. };
  67434. /**
  67435. * Destroy and release the resources associated with the audio ccontext.
  67436. */
  67437. AudioEngine.prototype.dispose = function () {
  67438. if (this.canUseWebAudio && this._audioContextInitialized) {
  67439. if (this._connectedAnalyser && this._audioContext) {
  67440. this._connectedAnalyser.stopDebugCanvas();
  67441. this._connectedAnalyser.dispose();
  67442. this.masterGain.disconnect();
  67443. this.masterGain.connect(this._audioContext.destination);
  67444. this._connectedAnalyser = null;
  67445. }
  67446. this.masterGain.gain.value = 1;
  67447. }
  67448. this.WarnedWebAudioUnsupported = false;
  67449. this._hideMuteButton();
  67450. window.removeEventListener("resize", this._onResize);
  67451. this.onAudioUnlockedObservable.clear();
  67452. this.onAudioLockedObservable.clear();
  67453. };
  67454. /**
  67455. * Gets the global volume sets on the master gain.
  67456. * @returns the global volume if set or -1 otherwise
  67457. */
  67458. AudioEngine.prototype.getGlobalVolume = function () {
  67459. if (this.canUseWebAudio && this._audioContextInitialized) {
  67460. return this.masterGain.gain.value;
  67461. }
  67462. else {
  67463. return -1;
  67464. }
  67465. };
  67466. /**
  67467. * Sets the global volume of your experience (sets on the master gain).
  67468. * @param newVolume Defines the new global volume of the application
  67469. */
  67470. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67471. if (this.canUseWebAudio && this._audioContextInitialized) {
  67472. this.masterGain.gain.value = newVolume;
  67473. }
  67474. };
  67475. /**
  67476. * Connect the audio engine to an audio analyser allowing some amazing
  67477. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67478. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67479. * @param analyser The analyser to connect to the engine
  67480. */
  67481. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67482. if (this._connectedAnalyser) {
  67483. this._connectedAnalyser.stopDebugCanvas();
  67484. }
  67485. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67486. this._connectedAnalyser = analyser;
  67487. this.masterGain.disconnect();
  67488. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67489. }
  67490. };
  67491. return AudioEngine;
  67492. }());
  67493. BABYLON.AudioEngine = AudioEngine;
  67494. })(BABYLON || (BABYLON = {}));
  67495. //# sourceMappingURL=babylon.audioEngine.js.map
  67496. var BABYLON;
  67497. (function (BABYLON) {
  67498. /**
  67499. * Defines a sound that can be played in the application.
  67500. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67501. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67502. */
  67503. var Sound = /** @class */ (function () {
  67504. /**
  67505. * Create a sound and attach it to a scene
  67506. * @param name Name of your sound
  67507. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67508. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67509. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67510. */
  67511. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67512. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67513. var _this = this;
  67514. /**
  67515. * Does the sound autoplay once loaded.
  67516. */
  67517. this.autoplay = false;
  67518. /**
  67519. * Does the sound loop after it finishes playing once.
  67520. */
  67521. this.loop = false;
  67522. /**
  67523. * Does the sound use a custom attenuation curve to simulate the falloff
  67524. * happening when the source gets further away from the camera.
  67525. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67526. */
  67527. this.useCustomAttenuation = false;
  67528. /**
  67529. * Is this sound currently played.
  67530. */
  67531. this.isPlaying = false;
  67532. /**
  67533. * Is this sound currently paused.
  67534. */
  67535. this.isPaused = false;
  67536. /**
  67537. * Does this sound enables spatial sound.
  67538. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67539. */
  67540. this.spatialSound = false;
  67541. /**
  67542. * Define the reference distance the sound should be heard perfectly.
  67543. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67544. */
  67545. this.refDistance = 1;
  67546. /**
  67547. * Define the roll off factor of spatial sounds.
  67548. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67549. */
  67550. this.rolloffFactor = 1;
  67551. /**
  67552. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67553. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67554. */
  67555. this.maxDistance = 100;
  67556. /**
  67557. * Define the distance attenuation model the sound will follow.
  67558. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67559. */
  67560. this.distanceModel = "linear";
  67561. /**
  67562. * Observable event when the current playing sound finishes.
  67563. */
  67564. this.onEndedObservable = new BABYLON.Observable();
  67565. this._panningModel = "equalpower";
  67566. this._playbackRate = 1;
  67567. this._streaming = false;
  67568. this._startTime = 0;
  67569. this._startOffset = 0;
  67570. this._position = BABYLON.Vector3.Zero();
  67571. /** @hidden */
  67572. this._positionInEmitterSpace = false;
  67573. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67574. this._volume = 1;
  67575. this._isReadyToPlay = false;
  67576. this._isDirectional = false;
  67577. // Used if you'd like to create a directional sound.
  67578. // If not set, the sound will be omnidirectional
  67579. this._coneInnerAngle = 360;
  67580. this._coneOuterAngle = 360;
  67581. this._coneOuterGain = 0;
  67582. this._isOutputConnected = false;
  67583. this._urlType = "Unknown";
  67584. this.name = name;
  67585. this._scene = scene;
  67586. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67587. if (!compo) {
  67588. compo = new BABYLON.AudioSceneComponent(scene);
  67589. scene._addComponent(compo);
  67590. }
  67591. this._readyToPlayCallback = readyToPlayCallback;
  67592. // Default custom attenuation function is a linear attenuation
  67593. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67594. if (currentDistance < maxDistance) {
  67595. return currentVolume * (1 - currentDistance / maxDistance);
  67596. }
  67597. else {
  67598. return 0;
  67599. }
  67600. };
  67601. if (options) {
  67602. this.autoplay = options.autoplay || false;
  67603. this.loop = options.loop || false;
  67604. // if volume === 0, we need another way to check this option
  67605. if (options.volume !== undefined) {
  67606. this._volume = options.volume;
  67607. }
  67608. this.spatialSound = options.spatialSound || false;
  67609. this.maxDistance = options.maxDistance || 100;
  67610. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67611. this.rolloffFactor = options.rolloffFactor || 1;
  67612. this.refDistance = options.refDistance || 1;
  67613. this.distanceModel = options.distanceModel || "linear";
  67614. this._playbackRate = options.playbackRate || 1;
  67615. this._streaming = options.streaming || false;
  67616. }
  67617. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67618. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67619. this._soundGain.gain.value = this._volume;
  67620. this._inputAudioNode = this._soundGain;
  67621. this._outputAudioNode = this._soundGain;
  67622. if (this.spatialSound) {
  67623. this._createSpatialParameters();
  67624. }
  67625. this._scene.mainSoundTrack.AddSound(this);
  67626. var validParameter = true;
  67627. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67628. if (urlOrArrayBuffer) {
  67629. try {
  67630. if (typeof (urlOrArrayBuffer) === "string") {
  67631. this._urlType = "String";
  67632. }
  67633. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67634. this._urlType = "ArrayBuffer";
  67635. }
  67636. else if (urlOrArrayBuffer instanceof MediaStream) {
  67637. this._urlType = "MediaStream";
  67638. }
  67639. else if (Array.isArray(urlOrArrayBuffer)) {
  67640. this._urlType = "Array";
  67641. }
  67642. var urls = [];
  67643. var codecSupportedFound = false;
  67644. switch (this._urlType) {
  67645. case "MediaStream":
  67646. this._streaming = true;
  67647. this._isReadyToPlay = true;
  67648. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67649. if (this.autoplay) {
  67650. this.play();
  67651. }
  67652. if (this._readyToPlayCallback) {
  67653. this._readyToPlayCallback();
  67654. }
  67655. break;
  67656. case "ArrayBuffer":
  67657. if (urlOrArrayBuffer.byteLength > 0) {
  67658. codecSupportedFound = true;
  67659. this._soundLoaded(urlOrArrayBuffer);
  67660. }
  67661. break;
  67662. case "String":
  67663. urls.push(urlOrArrayBuffer);
  67664. case "Array":
  67665. if (urls.length === 0)
  67666. urls = urlOrArrayBuffer;
  67667. // If we found a supported format, we load it immediately and stop the loop
  67668. for (var i = 0; i < urls.length; i++) {
  67669. var url = urls[i];
  67670. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67671. codecSupportedFound = true;
  67672. }
  67673. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67674. codecSupportedFound = true;
  67675. }
  67676. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67677. codecSupportedFound = true;
  67678. }
  67679. if (url.indexOf("blob:") !== -1) {
  67680. codecSupportedFound = true;
  67681. }
  67682. if (codecSupportedFound) {
  67683. // Loading sound using XHR2
  67684. if (!this._streaming) {
  67685. this._scene._loadFile(url, function (data) {
  67686. _this._soundLoaded(data);
  67687. }, undefined, true, true, function (exception) {
  67688. if (exception) {
  67689. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67690. }
  67691. BABYLON.Tools.Error("Sound creation aborted.");
  67692. _this._scene.mainSoundTrack.RemoveSound(_this);
  67693. });
  67694. }
  67695. // Streaming sound using HTML5 Audio tag
  67696. else {
  67697. this._htmlAudioElement = new Audio(url);
  67698. this._htmlAudioElement.controls = false;
  67699. this._htmlAudioElement.loop = this.loop;
  67700. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67701. this._htmlAudioElement.preload = "auto";
  67702. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67703. _this._isReadyToPlay = true;
  67704. if (_this.autoplay) {
  67705. _this.play();
  67706. }
  67707. if (_this._readyToPlayCallback) {
  67708. _this._readyToPlayCallback();
  67709. }
  67710. });
  67711. document.body.appendChild(this._htmlAudioElement);
  67712. this._htmlAudioElement.load();
  67713. }
  67714. break;
  67715. }
  67716. }
  67717. break;
  67718. default:
  67719. validParameter = false;
  67720. break;
  67721. }
  67722. if (!validParameter) {
  67723. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67724. }
  67725. else {
  67726. if (!codecSupportedFound) {
  67727. this._isReadyToPlay = true;
  67728. // Simulating a ready to play event to avoid breaking code path
  67729. if (this._readyToPlayCallback) {
  67730. window.setTimeout(function () {
  67731. if (_this._readyToPlayCallback) {
  67732. _this._readyToPlayCallback();
  67733. }
  67734. }, 1000);
  67735. }
  67736. }
  67737. }
  67738. }
  67739. catch (ex) {
  67740. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67741. this._scene.mainSoundTrack.RemoveSound(this);
  67742. }
  67743. }
  67744. }
  67745. else {
  67746. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67747. this._scene.mainSoundTrack.AddSound(this);
  67748. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67749. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67750. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67751. }
  67752. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67753. if (this._readyToPlayCallback) {
  67754. window.setTimeout(function () {
  67755. if (_this._readyToPlayCallback) {
  67756. _this._readyToPlayCallback();
  67757. }
  67758. }, 1000);
  67759. }
  67760. }
  67761. }
  67762. /**
  67763. * Release the sound and its associated resources
  67764. */
  67765. Sound.prototype.dispose = function () {
  67766. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67767. if (this.isPlaying) {
  67768. this.stop();
  67769. }
  67770. this._isReadyToPlay = false;
  67771. if (this.soundTrackId === -1) {
  67772. this._scene.mainSoundTrack.RemoveSound(this);
  67773. }
  67774. else if (this._scene.soundTracks) {
  67775. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67776. }
  67777. if (this._soundGain) {
  67778. this._soundGain.disconnect();
  67779. this._soundGain = null;
  67780. }
  67781. if (this._soundPanner) {
  67782. this._soundPanner.disconnect();
  67783. this._soundPanner = null;
  67784. }
  67785. if (this._soundSource) {
  67786. this._soundSource.disconnect();
  67787. this._soundSource = null;
  67788. }
  67789. this._audioBuffer = null;
  67790. if (this._htmlAudioElement) {
  67791. this._htmlAudioElement.pause();
  67792. this._htmlAudioElement.src = "";
  67793. document.body.removeChild(this._htmlAudioElement);
  67794. }
  67795. if (this._streamingSource) {
  67796. this._streamingSource.disconnect();
  67797. }
  67798. if (this._connectedMesh && this._registerFunc) {
  67799. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67800. this._connectedMesh = null;
  67801. }
  67802. }
  67803. };
  67804. /**
  67805. * Gets if the sounds is ready to be played or not.
  67806. * @returns true if ready, otherwise false
  67807. */
  67808. Sound.prototype.isReady = function () {
  67809. return this._isReadyToPlay;
  67810. };
  67811. Sound.prototype._soundLoaded = function (audioData) {
  67812. var _this = this;
  67813. if (!BABYLON.Engine.audioEngine.audioContext) {
  67814. return;
  67815. }
  67816. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67817. _this._audioBuffer = buffer;
  67818. _this._isReadyToPlay = true;
  67819. if (_this.autoplay) {
  67820. _this.play();
  67821. }
  67822. if (_this._readyToPlayCallback) {
  67823. _this._readyToPlayCallback();
  67824. }
  67825. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67826. };
  67827. /**
  67828. * Sets the data of the sound from an audiobuffer
  67829. * @param audioBuffer The audioBuffer containing the data
  67830. */
  67831. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67832. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67833. this._audioBuffer = audioBuffer;
  67834. this._isReadyToPlay = true;
  67835. }
  67836. };
  67837. /**
  67838. * Updates the current sounds options such as maxdistance, loop...
  67839. * @param options A JSON object containing values named as the object properties
  67840. */
  67841. Sound.prototype.updateOptions = function (options) {
  67842. if (options) {
  67843. this.loop = options.loop || this.loop;
  67844. this.maxDistance = options.maxDistance || this.maxDistance;
  67845. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67846. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67847. this.refDistance = options.refDistance || this.refDistance;
  67848. this.distanceModel = options.distanceModel || this.distanceModel;
  67849. this._playbackRate = options.playbackRate || this._playbackRate;
  67850. this._updateSpatialParameters();
  67851. if (this.isPlaying) {
  67852. if (this._streaming && this._htmlAudioElement) {
  67853. this._htmlAudioElement.playbackRate = this._playbackRate;
  67854. }
  67855. else {
  67856. if (this._soundSource) {
  67857. this._soundSource.playbackRate.value = this._playbackRate;
  67858. }
  67859. }
  67860. }
  67861. }
  67862. };
  67863. Sound.prototype._createSpatialParameters = function () {
  67864. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67865. if (this._scene.headphone) {
  67866. this._panningModel = "HRTF";
  67867. }
  67868. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67869. this._updateSpatialParameters();
  67870. this._soundPanner.connect(this._outputAudioNode);
  67871. this._inputAudioNode = this._soundPanner;
  67872. }
  67873. };
  67874. Sound.prototype._updateSpatialParameters = function () {
  67875. if (this.spatialSound && this._soundPanner) {
  67876. if (this.useCustomAttenuation) {
  67877. // Tricks to disable in a way embedded Web Audio attenuation
  67878. this._soundPanner.distanceModel = "linear";
  67879. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67880. this._soundPanner.refDistance = 1;
  67881. this._soundPanner.rolloffFactor = 1;
  67882. this._soundPanner.panningModel = this._panningModel;
  67883. }
  67884. else {
  67885. this._soundPanner.distanceModel = this.distanceModel;
  67886. this._soundPanner.maxDistance = this.maxDistance;
  67887. this._soundPanner.refDistance = this.refDistance;
  67888. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67889. this._soundPanner.panningModel = this._panningModel;
  67890. }
  67891. }
  67892. };
  67893. /**
  67894. * Switch the panning model to HRTF:
  67895. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  67896. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67897. */
  67898. Sound.prototype.switchPanningModelToHRTF = function () {
  67899. this._panningModel = "HRTF";
  67900. this._switchPanningModel();
  67901. };
  67902. /**
  67903. * Switch the panning model to Equal Power:
  67904. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  67905. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67906. */
  67907. Sound.prototype.switchPanningModelToEqualPower = function () {
  67908. this._panningModel = "equalpower";
  67909. this._switchPanningModel();
  67910. };
  67911. Sound.prototype._switchPanningModel = function () {
  67912. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67913. this._soundPanner.panningModel = this._panningModel;
  67914. }
  67915. };
  67916. /**
  67917. * Connect this sound to a sound track audio node like gain...
  67918. * @param soundTrackAudioNode the sound track audio node to connect to
  67919. */
  67920. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67921. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67922. if (this._isOutputConnected) {
  67923. this._outputAudioNode.disconnect();
  67924. }
  67925. this._outputAudioNode.connect(soundTrackAudioNode);
  67926. this._isOutputConnected = true;
  67927. }
  67928. };
  67929. /**
  67930. * Transform this sound into a directional source
  67931. * @param coneInnerAngle Size of the inner cone in degree
  67932. * @param coneOuterAngle Size of the outer cone in degree
  67933. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67934. */
  67935. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67936. if (coneOuterAngle < coneInnerAngle) {
  67937. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67938. return;
  67939. }
  67940. this._coneInnerAngle = coneInnerAngle;
  67941. this._coneOuterAngle = coneOuterAngle;
  67942. this._coneOuterGain = coneOuterGain;
  67943. this._isDirectional = true;
  67944. if (this.isPlaying && this.loop) {
  67945. this.stop();
  67946. this.play();
  67947. }
  67948. };
  67949. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67950. /**
  67951. * Gets or sets the inner angle for the directional cone.
  67952. */
  67953. get: function () {
  67954. return this._coneInnerAngle;
  67955. },
  67956. /**
  67957. * Gets or sets the inner angle for the directional cone.
  67958. */
  67959. set: function (value) {
  67960. if (value != this._coneInnerAngle) {
  67961. if (this._coneOuterAngle < value) {
  67962. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67963. return;
  67964. }
  67965. this._coneInnerAngle = value;
  67966. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67967. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67968. }
  67969. }
  67970. },
  67971. enumerable: true,
  67972. configurable: true
  67973. });
  67974. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  67975. /**
  67976. * Gets or sets the outer angle for the directional cone.
  67977. */
  67978. get: function () {
  67979. return this._coneOuterAngle;
  67980. },
  67981. /**
  67982. * Gets or sets the outer angle for the directional cone.
  67983. */
  67984. set: function (value) {
  67985. if (value != this._coneOuterAngle) {
  67986. if (value < this._coneInnerAngle) {
  67987. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67988. return;
  67989. }
  67990. this._coneOuterAngle = value;
  67991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67992. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67993. }
  67994. }
  67995. },
  67996. enumerable: true,
  67997. configurable: true
  67998. });
  67999. /**
  68000. * Sets the position of the emitter if spatial sound is enabled
  68001. * @param newPosition Defines the new posisiton
  68002. */
  68003. Sound.prototype.setPosition = function (newPosition) {
  68004. this._position = newPosition;
  68005. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68006. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68007. }
  68008. };
  68009. /**
  68010. * Sets the local direction of the emitter if spatial sound is enabled
  68011. * @param newLocalDirection Defines the new local direction
  68012. */
  68013. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68014. this._localDirection = newLocalDirection;
  68015. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68016. this._updateDirection();
  68017. }
  68018. };
  68019. Sound.prototype._updateDirection = function () {
  68020. if (!this._connectedMesh || !this._soundPanner) {
  68021. return;
  68022. }
  68023. var mat = this._connectedMesh.getWorldMatrix();
  68024. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68025. direction.normalize();
  68026. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68027. };
  68028. /** @hidden */
  68029. Sound.prototype.updateDistanceFromListener = function () {
  68030. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68031. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68032. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68033. }
  68034. };
  68035. /**
  68036. * Sets a new custom attenuation function for the sound.
  68037. * @param callback Defines the function used for the attenuation
  68038. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68039. */
  68040. Sound.prototype.setAttenuationFunction = function (callback) {
  68041. this._customAttenuationFunction = callback;
  68042. };
  68043. /**
  68044. * Play the sound
  68045. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68046. * @param offset (optional) Start the sound setting it at a specific time
  68047. */
  68048. Sound.prototype.play = function (time, offset) {
  68049. var _this = this;
  68050. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68051. try {
  68052. if (this._startOffset < 0) {
  68053. time = -this._startOffset;
  68054. this._startOffset = 0;
  68055. }
  68056. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68057. if (!this._soundSource || !this._streamingSource) {
  68058. if (this.spatialSound && this._soundPanner) {
  68059. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68060. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68061. }
  68062. if (this._isDirectional) {
  68063. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68064. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68065. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68066. if (this._connectedMesh) {
  68067. this._updateDirection();
  68068. }
  68069. else {
  68070. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68071. }
  68072. }
  68073. }
  68074. }
  68075. if (this._streaming) {
  68076. if (!this._streamingSource) {
  68077. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  68078. this._htmlAudioElement.onended = function () { _this._onended(); };
  68079. this._htmlAudioElement.playbackRate = this._playbackRate;
  68080. }
  68081. this._streamingSource.disconnect();
  68082. this._streamingSource.connect(this._inputAudioNode);
  68083. if (this._htmlAudioElement) {
  68084. // required to manage properly the new suspended default state of Chrome
  68085. // When the option 'streaming: true' is used, we need first to wait for
  68086. // the audio engine to be unlocked by a user gesture before trying to play
  68087. // an HTML Audio elememt
  68088. var tryToPlay = function () {
  68089. if (BABYLON.Engine.audioEngine.unlocked) {
  68090. var playPromise = _this._htmlAudioElement.play();
  68091. // In browsers that don’t yet support this functionality,
  68092. // playPromise won’t be defined.
  68093. if (playPromise !== undefined) {
  68094. playPromise.catch(function (error) {
  68095. // Automatic playback failed.
  68096. // Waiting for the audio engine to be unlocked by user click on unmute
  68097. BABYLON.Engine.audioEngine.lock();
  68098. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68099. });
  68100. }
  68101. }
  68102. else {
  68103. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68104. }
  68105. };
  68106. tryToPlay();
  68107. }
  68108. }
  68109. else {
  68110. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  68111. this._soundSource.buffer = this._audioBuffer;
  68112. this._soundSource.connect(this._inputAudioNode);
  68113. this._soundSource.loop = this.loop;
  68114. this._soundSource.playbackRate.value = this._playbackRate;
  68115. this._soundSource.onended = function () { _this._onended(); };
  68116. if (this._soundSource.buffer) {
  68117. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  68118. }
  68119. }
  68120. this._startTime = startTime;
  68121. this.isPlaying = true;
  68122. this.isPaused = false;
  68123. }
  68124. catch (ex) {
  68125. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  68126. }
  68127. }
  68128. };
  68129. Sound.prototype._onended = function () {
  68130. this.isPlaying = false;
  68131. if (this.onended) {
  68132. this.onended();
  68133. }
  68134. this.onEndedObservable.notifyObservers(this);
  68135. };
  68136. /**
  68137. * Stop the sound
  68138. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  68139. */
  68140. Sound.prototype.stop = function (time) {
  68141. if (this.isPlaying) {
  68142. if (this._streaming) {
  68143. if (this._htmlAudioElement) {
  68144. this._htmlAudioElement.pause();
  68145. // Test needed for Firefox or it will generate an Invalid State Error
  68146. if (this._htmlAudioElement.currentTime > 0) {
  68147. this._htmlAudioElement.currentTime = 0;
  68148. }
  68149. }
  68150. else {
  68151. this._streamingSource.disconnect();
  68152. }
  68153. }
  68154. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  68155. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68156. this._soundSource.stop(stopTime);
  68157. this._soundSource.onended = function () { };
  68158. if (!this.isPaused) {
  68159. this._startOffset = 0;
  68160. }
  68161. }
  68162. this.isPlaying = false;
  68163. }
  68164. };
  68165. /**
  68166. * Put the sound in pause
  68167. */
  68168. Sound.prototype.pause = function () {
  68169. if (this.isPlaying) {
  68170. this.isPaused = true;
  68171. if (this._streaming) {
  68172. if (this._htmlAudioElement) {
  68173. this._htmlAudioElement.pause();
  68174. }
  68175. else {
  68176. this._streamingSource.disconnect();
  68177. }
  68178. }
  68179. else if (BABYLON.Engine.audioEngine.audioContext) {
  68180. this.stop(0);
  68181. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  68182. }
  68183. }
  68184. };
  68185. /**
  68186. * Sets a dedicated volume for this sounds
  68187. * @param newVolume Define the new volume of the sound
  68188. * @param time Define in how long the sound should be at this value
  68189. */
  68190. Sound.prototype.setVolume = function (newVolume, time) {
  68191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  68192. if (time && BABYLON.Engine.audioEngine.audioContext) {
  68193. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  68194. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  68195. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  68196. }
  68197. else {
  68198. this._soundGain.gain.value = newVolume;
  68199. }
  68200. }
  68201. this._volume = newVolume;
  68202. };
  68203. /**
  68204. * Set the sound play back rate
  68205. * @param newPlaybackRate Define the playback rate the sound should be played at
  68206. */
  68207. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  68208. this._playbackRate = newPlaybackRate;
  68209. if (this.isPlaying) {
  68210. if (this._streaming && this._htmlAudioElement) {
  68211. this._htmlAudioElement.playbackRate = this._playbackRate;
  68212. }
  68213. else if (this._soundSource) {
  68214. this._soundSource.playbackRate.value = this._playbackRate;
  68215. }
  68216. }
  68217. };
  68218. /**
  68219. * Gets the volume of the sound.
  68220. * @returns the volume of the sound
  68221. */
  68222. Sound.prototype.getVolume = function () {
  68223. return this._volume;
  68224. };
  68225. /**
  68226. * Attach the sound to a dedicated mesh
  68227. * @param meshToConnectTo The mesh to connect the sound with
  68228. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68229. */
  68230. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  68231. var _this = this;
  68232. if (this._connectedMesh && this._registerFunc) {
  68233. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68234. this._registerFunc = null;
  68235. }
  68236. this._connectedMesh = meshToConnectTo;
  68237. if (!this.spatialSound) {
  68238. this.spatialSound = true;
  68239. this._createSpatialParameters();
  68240. if (this.isPlaying && this.loop) {
  68241. this.stop();
  68242. this.play();
  68243. }
  68244. }
  68245. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  68246. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  68247. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  68248. };
  68249. /**
  68250. * Detach the sound from the previously attached mesh
  68251. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68252. */
  68253. Sound.prototype.detachFromMesh = function () {
  68254. if (this._connectedMesh && this._registerFunc) {
  68255. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68256. this._registerFunc = null;
  68257. this._connectedMesh = null;
  68258. }
  68259. };
  68260. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  68261. if (!node.getBoundingInfo) {
  68262. return;
  68263. }
  68264. var mesh = node;
  68265. if (this._positionInEmitterSpace) {
  68266. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  68267. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  68268. }
  68269. else {
  68270. var boundingInfo = mesh.getBoundingInfo();
  68271. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  68272. }
  68273. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  68274. this._updateDirection();
  68275. }
  68276. };
  68277. /**
  68278. * Clone the current sound in the scene.
  68279. * @returns the new sound clone
  68280. */
  68281. Sound.prototype.clone = function () {
  68282. var _this = this;
  68283. if (!this._streaming) {
  68284. var setBufferAndRun = function () {
  68285. if (_this._isReadyToPlay) {
  68286. clonedSound._audioBuffer = _this.getAudioBuffer();
  68287. clonedSound._isReadyToPlay = true;
  68288. if (clonedSound.autoplay) {
  68289. clonedSound.play();
  68290. }
  68291. }
  68292. else {
  68293. window.setTimeout(setBufferAndRun, 300);
  68294. }
  68295. };
  68296. var currentOptions = {
  68297. autoplay: this.autoplay, loop: this.loop,
  68298. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68299. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68300. refDistance: this.refDistance, distanceModel: this.distanceModel
  68301. };
  68302. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68303. if (this.useCustomAttenuation) {
  68304. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68305. }
  68306. clonedSound.setPosition(this._position);
  68307. clonedSound.setPlaybackRate(this._playbackRate);
  68308. setBufferAndRun();
  68309. return clonedSound;
  68310. }
  68311. // Can't clone a streaming sound
  68312. else {
  68313. return null;
  68314. }
  68315. };
  68316. /**
  68317. * Gets the current underlying audio buffer containing the data
  68318. * @returns the audio buffer
  68319. */
  68320. Sound.prototype.getAudioBuffer = function () {
  68321. return this._audioBuffer;
  68322. };
  68323. /**
  68324. * Serializes the Sound in a JSON representation
  68325. * @returns the JSON representation of the sound
  68326. */
  68327. Sound.prototype.serialize = function () {
  68328. var serializationObject = {
  68329. name: this.name,
  68330. url: this.name,
  68331. autoplay: this.autoplay,
  68332. loop: this.loop,
  68333. volume: this._volume,
  68334. spatialSound: this.spatialSound,
  68335. maxDistance: this.maxDistance,
  68336. rolloffFactor: this.rolloffFactor,
  68337. refDistance: this.refDistance,
  68338. distanceModel: this.distanceModel,
  68339. playbackRate: this._playbackRate,
  68340. panningModel: this._panningModel,
  68341. soundTrackId: this.soundTrackId
  68342. };
  68343. if (this.spatialSound) {
  68344. if (this._connectedMesh)
  68345. serializationObject.connectedMeshId = this._connectedMesh.id;
  68346. serializationObject.position = this._position.asArray();
  68347. serializationObject.refDistance = this.refDistance;
  68348. serializationObject.distanceModel = this.distanceModel;
  68349. serializationObject.isDirectional = this._isDirectional;
  68350. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68351. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68352. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68353. serializationObject.coneOuterGain = this._coneOuterGain;
  68354. }
  68355. return serializationObject;
  68356. };
  68357. /**
  68358. * Parse a JSON representation of a sound to innstantiate in a given scene
  68359. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68360. * @param scene Define the scene the new parsed sound should be created in
  68361. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68362. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68363. * @returns the newly parsed sound
  68364. */
  68365. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68366. var soundName = parsedSound.name;
  68367. var soundUrl;
  68368. if (parsedSound.url) {
  68369. soundUrl = rootUrl + parsedSound.url;
  68370. }
  68371. else {
  68372. soundUrl = rootUrl + soundName;
  68373. }
  68374. var options = {
  68375. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68376. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68377. rolloffFactor: parsedSound.rolloffFactor,
  68378. refDistance: parsedSound.refDistance,
  68379. distanceModel: parsedSound.distanceModel,
  68380. playbackRate: parsedSound.playbackRate
  68381. };
  68382. var newSound;
  68383. if (!sourceSound) {
  68384. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68385. scene._addPendingData(newSound);
  68386. }
  68387. else {
  68388. var setBufferAndRun = function () {
  68389. if (sourceSound._isReadyToPlay) {
  68390. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68391. newSound._isReadyToPlay = true;
  68392. if (newSound.autoplay) {
  68393. newSound.play();
  68394. }
  68395. }
  68396. else {
  68397. window.setTimeout(setBufferAndRun, 300);
  68398. }
  68399. };
  68400. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68401. setBufferAndRun();
  68402. }
  68403. if (parsedSound.position) {
  68404. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68405. newSound.setPosition(soundPosition);
  68406. }
  68407. if (parsedSound.isDirectional) {
  68408. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68409. if (parsedSound.localDirectionToMesh) {
  68410. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68411. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68412. }
  68413. }
  68414. if (parsedSound.connectedMeshId) {
  68415. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68416. if (connectedMesh) {
  68417. newSound.attachToMesh(connectedMesh);
  68418. }
  68419. }
  68420. return newSound;
  68421. };
  68422. return Sound;
  68423. }());
  68424. BABYLON.Sound = Sound;
  68425. })(BABYLON || (BABYLON = {}));
  68426. //# sourceMappingURL=babylon.sound.js.map
  68427. var BABYLON;
  68428. (function (BABYLON) {
  68429. /**
  68430. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68431. * It will be also used in a future release to apply effects on a specific track.
  68432. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68433. */
  68434. var SoundTrack = /** @class */ (function () {
  68435. /**
  68436. * Creates a new sound track.
  68437. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68438. * @param scene Define the scene the sound track belongs to
  68439. * @param options
  68440. */
  68441. function SoundTrack(scene, options) {
  68442. if (options === void 0) { options = {}; }
  68443. /**
  68444. * The unique identifier of the sound track in the scene.
  68445. */
  68446. this.id = -1;
  68447. this._isMainTrack = false;
  68448. this._isInitialized = false;
  68449. this._scene = scene;
  68450. this.soundCollection = new Array();
  68451. this._options = options;
  68452. if (!this._isMainTrack && this._scene.soundTracks) {
  68453. this._scene.soundTracks.push(this);
  68454. this.id = this._scene.soundTracks.length - 1;
  68455. }
  68456. }
  68457. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68458. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68459. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68460. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68461. if (this._options) {
  68462. if (this._options.volume) {
  68463. this._outputAudioNode.gain.value = this._options.volume;
  68464. }
  68465. if (this._options.mainTrack) {
  68466. this._isMainTrack = this._options.mainTrack;
  68467. }
  68468. }
  68469. this._isInitialized = true;
  68470. }
  68471. };
  68472. /**
  68473. * Release the sound track and its associated resources
  68474. */
  68475. SoundTrack.prototype.dispose = function () {
  68476. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68477. if (this._connectedAnalyser) {
  68478. this._connectedAnalyser.stopDebugCanvas();
  68479. }
  68480. while (this.soundCollection.length) {
  68481. this.soundCollection[0].dispose();
  68482. }
  68483. if (this._outputAudioNode) {
  68484. this._outputAudioNode.disconnect();
  68485. }
  68486. this._outputAudioNode = null;
  68487. }
  68488. };
  68489. /**
  68490. * Adds a sound to this sound track
  68491. * @param sound define the cound to add
  68492. * @ignoreNaming
  68493. */
  68494. SoundTrack.prototype.AddSound = function (sound) {
  68495. if (!this._isInitialized) {
  68496. this._initializeSoundTrackAudioGraph();
  68497. }
  68498. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68499. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68500. }
  68501. if (sound.soundTrackId) {
  68502. if (sound.soundTrackId === -1) {
  68503. this._scene.mainSoundTrack.RemoveSound(sound);
  68504. }
  68505. else if (this._scene.soundTracks) {
  68506. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68507. }
  68508. }
  68509. this.soundCollection.push(sound);
  68510. sound.soundTrackId = this.id;
  68511. };
  68512. /**
  68513. * Removes a sound to this sound track
  68514. * @param sound define the cound to remove
  68515. * @ignoreNaming
  68516. */
  68517. SoundTrack.prototype.RemoveSound = function (sound) {
  68518. var index = this.soundCollection.indexOf(sound);
  68519. if (index !== -1) {
  68520. this.soundCollection.splice(index, 1);
  68521. }
  68522. };
  68523. /**
  68524. * Set a global volume for the full sound track.
  68525. * @param newVolume Define the new volume of the sound track
  68526. */
  68527. SoundTrack.prototype.setVolume = function (newVolume) {
  68528. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68529. this._outputAudioNode.gain.value = newVolume;
  68530. }
  68531. };
  68532. /**
  68533. * Switch the panning model to HRTF:
  68534. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68535. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68536. */
  68537. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68538. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68539. for (var i = 0; i < this.soundCollection.length; i++) {
  68540. this.soundCollection[i].switchPanningModelToHRTF();
  68541. }
  68542. }
  68543. };
  68544. /**
  68545. * Switch the panning model to Equal Power:
  68546. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68547. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68548. */
  68549. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68550. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68551. for (var i = 0; i < this.soundCollection.length; i++) {
  68552. this.soundCollection[i].switchPanningModelToEqualPower();
  68553. }
  68554. }
  68555. };
  68556. /**
  68557. * Connect the sound track to an audio analyser allowing some amazing
  68558. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68559. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68560. * @param analyser The analyser to connect to the engine
  68561. */
  68562. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68563. if (this._connectedAnalyser) {
  68564. this._connectedAnalyser.stopDebugCanvas();
  68565. }
  68566. this._connectedAnalyser = analyser;
  68567. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68568. this._outputAudioNode.disconnect();
  68569. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68570. }
  68571. };
  68572. return SoundTrack;
  68573. }());
  68574. BABYLON.SoundTrack = SoundTrack;
  68575. })(BABYLON || (BABYLON = {}));
  68576. //# sourceMappingURL=babylon.soundtrack.js.map
  68577. var BABYLON;
  68578. (function (BABYLON) {
  68579. /**
  68580. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68581. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68582. */
  68583. var Analyser = /** @class */ (function () {
  68584. /**
  68585. * Creates a new analyser
  68586. * @param scene defines hosting scene
  68587. */
  68588. function Analyser(scene) {
  68589. /**
  68590. * Gets or sets the smoothing
  68591. * @ignorenaming
  68592. */
  68593. this.SMOOTHING = 0.75;
  68594. /**
  68595. * Gets or sets the FFT table size
  68596. * @ignorenaming
  68597. */
  68598. this.FFT_SIZE = 512;
  68599. /**
  68600. * Gets or sets the bar graph amplitude
  68601. * @ignorenaming
  68602. */
  68603. this.BARGRAPHAMPLITUDE = 256;
  68604. /**
  68605. * Gets or sets the position of the debug canvas
  68606. * @ignorenaming
  68607. */
  68608. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68609. /**
  68610. * Gets or sets the debug canvas size
  68611. * @ignorenaming
  68612. */
  68613. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68614. this._scene = scene;
  68615. this._audioEngine = BABYLON.Engine.audioEngine;
  68616. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68617. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68618. this._webAudioAnalyser.minDecibels = -140;
  68619. this._webAudioAnalyser.maxDecibels = 0;
  68620. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68621. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68622. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68623. }
  68624. }
  68625. /**
  68626. * Get the number of data values you will have to play with for the visualization
  68627. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68628. * @returns a number
  68629. */
  68630. Analyser.prototype.getFrequencyBinCount = function () {
  68631. if (this._audioEngine.canUseWebAudio) {
  68632. return this._webAudioAnalyser.frequencyBinCount;
  68633. }
  68634. else {
  68635. return 0;
  68636. }
  68637. };
  68638. /**
  68639. * Gets the current frequency data as a byte array
  68640. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68641. * @returns a Uint8Array
  68642. */
  68643. Analyser.prototype.getByteFrequencyData = function () {
  68644. if (this._audioEngine.canUseWebAudio) {
  68645. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68646. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68647. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68648. }
  68649. return this._byteFreqs;
  68650. };
  68651. /**
  68652. * Gets the current waveform as a byte array
  68653. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68654. * @returns a Uint8Array
  68655. */
  68656. Analyser.prototype.getByteTimeDomainData = function () {
  68657. if (this._audioEngine.canUseWebAudio) {
  68658. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68659. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68660. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68661. }
  68662. return this._byteTime;
  68663. };
  68664. /**
  68665. * Gets the current frequency data as a float array
  68666. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68667. * @returns a Float32Array
  68668. */
  68669. Analyser.prototype.getFloatFrequencyData = function () {
  68670. if (this._audioEngine.canUseWebAudio) {
  68671. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68672. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68673. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68674. }
  68675. return this._floatFreqs;
  68676. };
  68677. /**
  68678. * Renders the debug canvas
  68679. */
  68680. Analyser.prototype.drawDebugCanvas = function () {
  68681. var _this = this;
  68682. if (this._audioEngine.canUseWebAudio) {
  68683. if (!this._debugCanvas) {
  68684. this._debugCanvas = document.createElement("canvas");
  68685. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68686. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68687. this._debugCanvas.style.position = "absolute";
  68688. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68689. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68690. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68691. document.body.appendChild(this._debugCanvas);
  68692. this._registerFunc = function () {
  68693. _this.drawDebugCanvas();
  68694. };
  68695. this._scene.registerBeforeRender(this._registerFunc);
  68696. }
  68697. if (this._registerFunc && this._debugCanvasContext) {
  68698. var workingArray = this.getByteFrequencyData();
  68699. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68700. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68701. // Draw the frequency domain chart.
  68702. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68703. var value = workingArray[i];
  68704. var percent = value / this.BARGRAPHAMPLITUDE;
  68705. var height = this.DEBUGCANVASSIZE.height * percent;
  68706. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68707. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68708. var hue = i / this.getFrequencyBinCount() * 360;
  68709. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68710. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68711. }
  68712. }
  68713. }
  68714. };
  68715. /**
  68716. * Stops rendering the debug canvas and removes it
  68717. */
  68718. Analyser.prototype.stopDebugCanvas = function () {
  68719. if (this._debugCanvas) {
  68720. if (this._registerFunc) {
  68721. this._scene.unregisterBeforeRender(this._registerFunc);
  68722. this._registerFunc = null;
  68723. }
  68724. document.body.removeChild(this._debugCanvas);
  68725. this._debugCanvas = null;
  68726. this._debugCanvasContext = null;
  68727. }
  68728. };
  68729. /**
  68730. * Connects two audio nodes
  68731. * @param inputAudioNode defines first node to connect
  68732. * @param outputAudioNode defines second node to connect
  68733. */
  68734. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68735. if (this._audioEngine.canUseWebAudio) {
  68736. inputAudioNode.connect(this._webAudioAnalyser);
  68737. this._webAudioAnalyser.connect(outputAudioNode);
  68738. }
  68739. };
  68740. /**
  68741. * Releases all associated resources
  68742. */
  68743. Analyser.prototype.dispose = function () {
  68744. if (this._audioEngine.canUseWebAudio) {
  68745. this._webAudioAnalyser.disconnect();
  68746. }
  68747. };
  68748. return Analyser;
  68749. }());
  68750. BABYLON.Analyser = Analyser;
  68751. })(BABYLON || (BABYLON = {}));
  68752. //# sourceMappingURL=babylon.analyser.js.map
  68753. var BABYLON;
  68754. (function (BABYLON) {
  68755. /**
  68756. * Wraps one or more Sound objects and selects one with random weight for playback.
  68757. */
  68758. var WeightedSound = /** @class */ (function () {
  68759. /**
  68760. * Creates a new WeightedSound from the list of sounds given.
  68761. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68762. * @param sounds Array of Sounds that will be selected from.
  68763. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68764. */
  68765. function WeightedSound(loop, sounds, weights) {
  68766. var _this = this;
  68767. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68768. this.loop = false;
  68769. this._coneInnerAngle = 360;
  68770. this._coneOuterAngle = 360;
  68771. this._volume = 1;
  68772. /** A Sound is currently playing. */
  68773. this.isPlaying = false;
  68774. /** A Sound is currently paused. */
  68775. this.isPaused = false;
  68776. this._sounds = [];
  68777. this._weights = [];
  68778. if (sounds.length !== weights.length) {
  68779. throw new Error('Sounds length does not equal weights length');
  68780. }
  68781. this.loop = loop;
  68782. this._weights = weights;
  68783. // Normalize the weights
  68784. var weightSum = 0;
  68785. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68786. var weight = weights_1[_i];
  68787. weightSum += weight;
  68788. }
  68789. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68790. for (var i = 0; i < this._weights.length; i++) {
  68791. this._weights[i] *= invWeightSum;
  68792. }
  68793. this._sounds = sounds;
  68794. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68795. var sound = _b[_a];
  68796. sound.onEndedObservable.add(function () { _this._onended(); });
  68797. }
  68798. }
  68799. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68800. /**
  68801. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68802. */
  68803. get: function () {
  68804. return this._coneInnerAngle;
  68805. },
  68806. /**
  68807. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68808. */
  68809. set: function (value) {
  68810. if (value !== this._coneInnerAngle) {
  68811. if (this._coneOuterAngle < value) {
  68812. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68813. return;
  68814. }
  68815. this._coneInnerAngle = value;
  68816. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68817. var sound = _a[_i];
  68818. sound.directionalConeInnerAngle = value;
  68819. }
  68820. }
  68821. },
  68822. enumerable: true,
  68823. configurable: true
  68824. });
  68825. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68826. /**
  68827. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68828. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68829. */
  68830. get: function () {
  68831. return this._coneOuterAngle;
  68832. },
  68833. /**
  68834. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68835. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68836. */
  68837. set: function (value) {
  68838. if (value !== this._coneOuterAngle) {
  68839. if (value < this._coneInnerAngle) {
  68840. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68841. return;
  68842. }
  68843. this._coneOuterAngle = value;
  68844. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68845. var sound = _a[_i];
  68846. sound.directionalConeOuterAngle = value;
  68847. }
  68848. }
  68849. },
  68850. enumerable: true,
  68851. configurable: true
  68852. });
  68853. Object.defineProperty(WeightedSound.prototype, "volume", {
  68854. /**
  68855. * Playback volume.
  68856. */
  68857. get: function () {
  68858. return this._volume;
  68859. },
  68860. /**
  68861. * Playback volume.
  68862. */
  68863. set: function (value) {
  68864. if (value !== this._volume) {
  68865. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68866. var sound = _a[_i];
  68867. sound.setVolume(value);
  68868. }
  68869. }
  68870. },
  68871. enumerable: true,
  68872. configurable: true
  68873. });
  68874. WeightedSound.prototype._onended = function () {
  68875. if (this._currentIndex !== undefined) {
  68876. this._sounds[this._currentIndex].autoplay = false;
  68877. }
  68878. if (this.loop && this.isPlaying) {
  68879. this.play();
  68880. }
  68881. else {
  68882. this.isPlaying = false;
  68883. }
  68884. };
  68885. /**
  68886. * Suspend playback
  68887. */
  68888. WeightedSound.prototype.pause = function () {
  68889. this.isPaused = true;
  68890. if (this._currentIndex !== undefined) {
  68891. this._sounds[this._currentIndex].pause();
  68892. }
  68893. };
  68894. /**
  68895. * Stop playback
  68896. */
  68897. WeightedSound.prototype.stop = function () {
  68898. this.isPlaying = false;
  68899. if (this._currentIndex !== undefined) {
  68900. this._sounds[this._currentIndex].stop();
  68901. }
  68902. };
  68903. /**
  68904. * Start playback.
  68905. * @param startOffset Position the clip head at a specific time in seconds.
  68906. */
  68907. WeightedSound.prototype.play = function (startOffset) {
  68908. if (!this.isPaused) {
  68909. this.stop();
  68910. var randomValue = Math.random();
  68911. var total = 0;
  68912. for (var i = 0; i < this._weights.length; i++) {
  68913. total += this._weights[i];
  68914. if (randomValue <= total) {
  68915. this._currentIndex = i;
  68916. break;
  68917. }
  68918. }
  68919. }
  68920. var sound = this._sounds[this._currentIndex];
  68921. if (sound.isReady()) {
  68922. sound.play(0, this.isPaused ? undefined : startOffset);
  68923. }
  68924. else {
  68925. sound.autoplay = true;
  68926. }
  68927. this.isPlaying = true;
  68928. this.isPaused = false;
  68929. };
  68930. return WeightedSound;
  68931. }());
  68932. BABYLON.WeightedSound = WeightedSound;
  68933. })(BABYLON || (BABYLON = {}));
  68934. //# sourceMappingURL=babylon.weightedsound.js.map
  68935. var BABYLON;
  68936. (function (BABYLON) {
  68937. // Adds the parser to the scene parsers.
  68938. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68939. // TODO: add sound
  68940. var loadedSounds = [];
  68941. var loadedSound;
  68942. container.sounds = container.sounds || [];
  68943. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68944. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68945. var parsedSound = parsedData.sounds[index];
  68946. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68947. if (!parsedSound.url)
  68948. parsedSound.url = parsedSound.name;
  68949. if (!loadedSounds[parsedSound.url]) {
  68950. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68951. loadedSounds[parsedSound.url] = loadedSound;
  68952. container.sounds.push(loadedSound);
  68953. }
  68954. else {
  68955. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68956. }
  68957. }
  68958. else {
  68959. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68960. }
  68961. }
  68962. }
  68963. loadedSounds = [];
  68964. });
  68965. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68966. get: function () {
  68967. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68968. if (!compo) {
  68969. compo = new AudioSceneComponent(this);
  68970. this._addComponent(compo);
  68971. }
  68972. if (!this._mainSoundTrack) {
  68973. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  68974. }
  68975. return this._mainSoundTrack;
  68976. },
  68977. enumerable: true,
  68978. configurable: true
  68979. });
  68980. BABYLON.Scene.prototype.getSoundByName = function (name) {
  68981. var index;
  68982. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  68983. if (this.mainSoundTrack.soundCollection[index].name === name) {
  68984. return this.mainSoundTrack.soundCollection[index];
  68985. }
  68986. }
  68987. if (this.soundTracks) {
  68988. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  68989. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  68990. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  68991. return this.soundTracks[sdIndex].soundCollection[index];
  68992. }
  68993. }
  68994. }
  68995. }
  68996. return null;
  68997. };
  68998. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  68999. get: function () {
  69000. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69001. if (!compo) {
  69002. compo = new AudioSceneComponent(this);
  69003. this._addComponent(compo);
  69004. }
  69005. return compo.audioEnabled;
  69006. },
  69007. set: function (value) {
  69008. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69009. if (!compo) {
  69010. compo = new AudioSceneComponent(this);
  69011. this._addComponent(compo);
  69012. }
  69013. if (value) {
  69014. compo.enableAudio();
  69015. }
  69016. else {
  69017. compo.disableAudio();
  69018. }
  69019. },
  69020. enumerable: true,
  69021. configurable: true
  69022. });
  69023. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69024. get: function () {
  69025. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69026. if (!compo) {
  69027. compo = new AudioSceneComponent(this);
  69028. this._addComponent(compo);
  69029. }
  69030. return compo.headphone;
  69031. },
  69032. set: function (value) {
  69033. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69034. if (!compo) {
  69035. compo = new AudioSceneComponent(this);
  69036. this._addComponent(compo);
  69037. }
  69038. if (value) {
  69039. compo.switchAudioModeForHeadphones();
  69040. }
  69041. else {
  69042. compo.switchAudioModeForNormalSpeakers();
  69043. }
  69044. },
  69045. enumerable: true,
  69046. configurable: true
  69047. });
  69048. /**
  69049. * Defines the sound scene component responsible to manage any sounds
  69050. * in a given scene.
  69051. */
  69052. var AudioSceneComponent = /** @class */ (function () {
  69053. /**
  69054. * Creates a new instance of the component for the given scene
  69055. * @param scene Defines the scene to register the component in
  69056. */
  69057. function AudioSceneComponent(scene) {
  69058. /**
  69059. * The component name helpfull to identify the component in the list of scene components.
  69060. */
  69061. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69062. this._audioEnabled = true;
  69063. this._headphone = false;
  69064. this.scene = scene;
  69065. scene.soundTracks = new Array();
  69066. scene.sounds = new Array();
  69067. }
  69068. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69069. /**
  69070. * Gets whether audio is enabled or not.
  69071. * Please use related enable/disable method to switch state.
  69072. */
  69073. get: function () {
  69074. return this._audioEnabled;
  69075. },
  69076. enumerable: true,
  69077. configurable: true
  69078. });
  69079. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  69080. /**
  69081. * Gets whether audio is outputing to headphone or not.
  69082. * Please use the according Switch methods to change output.
  69083. */
  69084. get: function () {
  69085. return this._headphone;
  69086. },
  69087. enumerable: true,
  69088. configurable: true
  69089. });
  69090. /**
  69091. * Registers the component in a given scene
  69092. */
  69093. AudioSceneComponent.prototype.register = function () {
  69094. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  69095. };
  69096. /**
  69097. * Rebuilds the elements related to this component in case of
  69098. * context lost for instance.
  69099. */
  69100. AudioSceneComponent.prototype.rebuild = function () {
  69101. // Nothing to do here. (Not rendering related)
  69102. };
  69103. /**
  69104. * Serializes the component data to the specified json object
  69105. * @param serializationObject The object to serialize to
  69106. */
  69107. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  69108. serializationObject.sounds = [];
  69109. if (this.scene.soundTracks) {
  69110. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  69111. var soundtrack = this.scene.soundTracks[index];
  69112. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69113. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69114. }
  69115. }
  69116. }
  69117. };
  69118. /**
  69119. * Adds all the element from the container to the scene
  69120. * @param container the container holding the elements
  69121. */
  69122. AudioSceneComponent.prototype.addFromContainer = function (container) {
  69123. var _this = this;
  69124. if (!container.sounds) {
  69125. return;
  69126. }
  69127. container.sounds.forEach(function (sound) {
  69128. sound.play();
  69129. sound.autoplay = true;
  69130. _this.scene.mainSoundTrack.AddSound(sound);
  69131. });
  69132. };
  69133. /**
  69134. * Removes all the elements in the container from the scene
  69135. * @param container contains the elements to remove
  69136. */
  69137. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  69138. var _this = this;
  69139. if (!container.sounds) {
  69140. return;
  69141. }
  69142. container.sounds.forEach(function (sound) {
  69143. sound.stop();
  69144. sound.autoplay = false;
  69145. _this.scene.mainSoundTrack.RemoveSound(sound);
  69146. });
  69147. };
  69148. /**
  69149. * Disposes the component and the associated ressources.
  69150. */
  69151. AudioSceneComponent.prototype.dispose = function () {
  69152. var scene = this.scene;
  69153. if (scene._mainSoundTrack) {
  69154. scene.mainSoundTrack.dispose();
  69155. }
  69156. if (scene.soundTracks) {
  69157. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  69158. scene.soundTracks[scIndex].dispose();
  69159. }
  69160. }
  69161. };
  69162. /**
  69163. * Disables audio in the associated scene.
  69164. */
  69165. AudioSceneComponent.prototype.disableAudio = function () {
  69166. var scene = this.scene;
  69167. this._audioEnabled = false;
  69168. var i;
  69169. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69170. scene.mainSoundTrack.soundCollection[i].pause();
  69171. }
  69172. if (scene.soundTracks) {
  69173. for (i = 0; i < scene.soundTracks.length; i++) {
  69174. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69175. scene.soundTracks[i].soundCollection[j].pause();
  69176. }
  69177. }
  69178. }
  69179. };
  69180. /**
  69181. * Enables audio in the associated scene.
  69182. */
  69183. AudioSceneComponent.prototype.enableAudio = function () {
  69184. var scene = this.scene;
  69185. this._audioEnabled = true;
  69186. var i;
  69187. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69188. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  69189. scene.mainSoundTrack.soundCollection[i].play();
  69190. }
  69191. }
  69192. if (scene.soundTracks) {
  69193. for (i = 0; i < scene.soundTracks.length; i++) {
  69194. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69195. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  69196. scene.soundTracks[i].soundCollection[j].play();
  69197. }
  69198. }
  69199. }
  69200. }
  69201. };
  69202. /**
  69203. * Switch audio to headphone output.
  69204. */
  69205. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  69206. var scene = this.scene;
  69207. this._headphone = true;
  69208. scene.mainSoundTrack.switchPanningModelToHRTF();
  69209. if (scene.soundTracks) {
  69210. for (var i = 0; i < scene.soundTracks.length; i++) {
  69211. scene.soundTracks[i].switchPanningModelToHRTF();
  69212. }
  69213. }
  69214. };
  69215. /**
  69216. * Switch audio to normal speakers.
  69217. */
  69218. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  69219. var scene = this.scene;
  69220. this._headphone = false;
  69221. scene.mainSoundTrack.switchPanningModelToEqualPower();
  69222. if (scene.soundTracks) {
  69223. for (var i = 0; i < scene.soundTracks.length; i++) {
  69224. scene.soundTracks[i].switchPanningModelToEqualPower();
  69225. }
  69226. }
  69227. };
  69228. AudioSceneComponent.prototype._afterRender = function () {
  69229. var scene = this.scene;
  69230. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  69231. return;
  69232. }
  69233. var listeningCamera;
  69234. var audioEngine = BABYLON.Engine.audioEngine;
  69235. if (scene.activeCameras.length > 0) {
  69236. listeningCamera = scene.activeCameras[0];
  69237. }
  69238. else {
  69239. listeningCamera = scene.activeCamera;
  69240. }
  69241. if (listeningCamera && audioEngine.audioContext) {
  69242. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  69243. // for VR cameras
  69244. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  69245. listeningCamera = listeningCamera.rigCameras[0];
  69246. }
  69247. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  69248. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  69249. cameraDirection.normalize();
  69250. // To avoid some errors on GearVR
  69251. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  69252. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  69253. }
  69254. var i;
  69255. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69256. var sound = scene.mainSoundTrack.soundCollection[i];
  69257. if (sound.useCustomAttenuation) {
  69258. sound.updateDistanceFromListener();
  69259. }
  69260. }
  69261. if (scene.soundTracks) {
  69262. for (i = 0; i < scene.soundTracks.length; i++) {
  69263. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69264. sound = scene.soundTracks[i].soundCollection[j];
  69265. if (sound.useCustomAttenuation) {
  69266. sound.updateDistanceFromListener();
  69267. }
  69268. }
  69269. }
  69270. }
  69271. }
  69272. };
  69273. return AudioSceneComponent;
  69274. }());
  69275. BABYLON.AudioSceneComponent = AudioSceneComponent;
  69276. })(BABYLON || (BABYLON = {}));
  69277. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  69278. var BABYLON;
  69279. (function (BABYLON) {
  69280. /**
  69281. * This defines an action helpful to play a defined sound on a triggered action.
  69282. */
  69283. var PlaySoundAction = /** @class */ (function (_super) {
  69284. __extends(PlaySoundAction, _super);
  69285. /**
  69286. * Instantiate the action
  69287. * @param triggerOptions defines the trigger options
  69288. * @param sound defines the sound to play
  69289. * @param condition defines the trigger related conditions
  69290. */
  69291. function PlaySoundAction(triggerOptions, sound, condition) {
  69292. var _this = _super.call(this, triggerOptions, condition) || this;
  69293. _this._sound = sound;
  69294. return _this;
  69295. }
  69296. /** @hidden */
  69297. PlaySoundAction.prototype._prepare = function () {
  69298. };
  69299. /**
  69300. * Execute the action and play the sound.
  69301. */
  69302. PlaySoundAction.prototype.execute = function () {
  69303. if (this._sound !== undefined)
  69304. this._sound.play();
  69305. };
  69306. /**
  69307. * Serializes the actions and its related information.
  69308. * @param parent defines the object to serialize in
  69309. * @returns the serialized object
  69310. */
  69311. PlaySoundAction.prototype.serialize = function (parent) {
  69312. return _super.prototype._serialize.call(this, {
  69313. name: "PlaySoundAction",
  69314. properties: [{ name: "sound", value: this._sound.name }]
  69315. }, parent);
  69316. };
  69317. return PlaySoundAction;
  69318. }(BABYLON.Action));
  69319. BABYLON.PlaySoundAction = PlaySoundAction;
  69320. /**
  69321. * This defines an action helpful to stop a defined sound on a triggered action.
  69322. */
  69323. var StopSoundAction = /** @class */ (function (_super) {
  69324. __extends(StopSoundAction, _super);
  69325. /**
  69326. * Instantiate the action
  69327. * @param triggerOptions defines the trigger options
  69328. * @param sound defines the sound to stop
  69329. * @param condition defines the trigger related conditions
  69330. */
  69331. function StopSoundAction(triggerOptions, sound, condition) {
  69332. var _this = _super.call(this, triggerOptions, condition) || this;
  69333. _this._sound = sound;
  69334. return _this;
  69335. }
  69336. /** @hidden */
  69337. StopSoundAction.prototype._prepare = function () {
  69338. };
  69339. /**
  69340. * Execute the action and stop the sound.
  69341. */
  69342. StopSoundAction.prototype.execute = function () {
  69343. if (this._sound !== undefined)
  69344. this._sound.stop();
  69345. };
  69346. /**
  69347. * Serializes the actions and its related information.
  69348. * @param parent defines the object to serialize in
  69349. * @returns the serialized object
  69350. */
  69351. StopSoundAction.prototype.serialize = function (parent) {
  69352. return _super.prototype._serialize.call(this, {
  69353. name: "StopSoundAction",
  69354. properties: [{ name: "sound", value: this._sound.name }]
  69355. }, parent);
  69356. };
  69357. return StopSoundAction;
  69358. }(BABYLON.Action));
  69359. BABYLON.StopSoundAction = StopSoundAction;
  69360. })(BABYLON || (BABYLON = {}));
  69361. //# sourceMappingURL=babylon.directAudioActions.js.map
  69362. var BABYLON;
  69363. (function (BABYLON) {
  69364. var CubeTexture = /** @class */ (function (_super) {
  69365. __extends(CubeTexture, _super);
  69366. /**
  69367. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69368. * as prefiltered data.
  69369. * @param rootUrl defines the url of the texture or the root name of the six images
  69370. * @param scene defines the scene the texture is attached to
  69371. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69372. * @param noMipmap defines if mipmaps should be created or not
  69373. * @param files defines the six files to load for the different faces
  69374. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69375. * @param onError defines a callback triggered in case of error during load
  69376. * @param format defines the internal format to use for the texture once loaded
  69377. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69378. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69379. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69380. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69381. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69382. * @return the cube texture
  69383. */
  69384. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69385. if (extensions === void 0) { extensions = null; }
  69386. if (noMipmap === void 0) { noMipmap = false; }
  69387. if (files === void 0) { files = null; }
  69388. if (onLoad === void 0) { onLoad = null; }
  69389. if (onError === void 0) { onError = null; }
  69390. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69391. if (prefiltered === void 0) { prefiltered = false; }
  69392. if (forcedExtension === void 0) { forcedExtension = null; }
  69393. if (createPolynomials === void 0) { createPolynomials = false; }
  69394. if (lodScale === void 0) { lodScale = 0.8; }
  69395. if (lodOffset === void 0) { lodOffset = 0; }
  69396. var _this = _super.call(this, scene) || this;
  69397. /**
  69398. * Gets or sets the center of the bounding box associated with the cube texture
  69399. * It must define where the camera used to render the texture was set
  69400. */
  69401. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69402. _this._rotationY = 0;
  69403. /** @hidden */
  69404. _this._prefiltered = false;
  69405. _this.name = rootUrl;
  69406. _this.url = rootUrl;
  69407. _this._noMipmap = noMipmap;
  69408. _this.hasAlpha = false;
  69409. _this._format = format;
  69410. _this.isCube = true;
  69411. _this._textureMatrix = BABYLON.Matrix.Identity();
  69412. _this._createPolynomials = createPolynomials;
  69413. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69414. if (!rootUrl && !files) {
  69415. return _this;
  69416. }
  69417. var lastDot = rootUrl.lastIndexOf(".");
  69418. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69419. var isDDS = (extension === ".dds");
  69420. var isEnv = (extension === ".env");
  69421. if (isEnv) {
  69422. _this.gammaSpace = false;
  69423. _this._prefiltered = false;
  69424. }
  69425. else {
  69426. _this._prefiltered = prefiltered;
  69427. if (prefiltered) {
  69428. _this.gammaSpace = false;
  69429. }
  69430. }
  69431. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69432. if (!files) {
  69433. if (!isEnv && !isDDS && !extensions) {
  69434. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69435. }
  69436. files = [];
  69437. if (extensions) {
  69438. for (var index = 0; index < extensions.length; index++) {
  69439. files.push(rootUrl + extensions[index]);
  69440. }
  69441. }
  69442. }
  69443. _this._files = files;
  69444. if (!_this._texture) {
  69445. if (!scene.useDelayedTextureLoading) {
  69446. if (prefiltered) {
  69447. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69448. }
  69449. else {
  69450. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69451. }
  69452. }
  69453. else {
  69454. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69455. }
  69456. }
  69457. else if (onLoad) {
  69458. if (_this._texture.isReady) {
  69459. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69460. }
  69461. else {
  69462. _this._texture.onLoadedObservable.add(onLoad);
  69463. }
  69464. }
  69465. return _this;
  69466. }
  69467. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69468. get: function () {
  69469. return this._boundingBoxSize;
  69470. },
  69471. /**
  69472. * Gets or sets the size of the bounding box associated with the cube texture
  69473. * When defined, the cubemap will switch to local mode
  69474. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69475. * @example https://www.babylonjs-playground.com/#RNASML
  69476. */
  69477. set: function (value) {
  69478. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69479. return;
  69480. }
  69481. this._boundingBoxSize = value;
  69482. var scene = this.getScene();
  69483. if (scene) {
  69484. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69485. }
  69486. },
  69487. enumerable: true,
  69488. configurable: true
  69489. });
  69490. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69491. /**
  69492. * Gets texture matrix rotation angle around Y axis radians.
  69493. */
  69494. get: function () {
  69495. return this._rotationY;
  69496. },
  69497. /**
  69498. * Sets texture matrix rotation angle around Y axis in radians.
  69499. */
  69500. set: function (value) {
  69501. this._rotationY = value;
  69502. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69503. },
  69504. enumerable: true,
  69505. configurable: true
  69506. });
  69507. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69508. var rootUrlKey = "";
  69509. files.forEach(function (url) { return rootUrlKey += url; });
  69510. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69511. };
  69512. /**
  69513. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69514. * @param url defines the url of the prefiltered texture
  69515. * @param scene defines the scene the texture is attached to
  69516. * @param forcedExtension defines the extension of the file if different from the url
  69517. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69518. * @return the prefiltered texture
  69519. */
  69520. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69521. if (forcedExtension === void 0) { forcedExtension = null; }
  69522. if (createPolynomials === void 0) { createPolynomials = true; }
  69523. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69524. };
  69525. // Methods
  69526. CubeTexture.prototype.delayLoad = function () {
  69527. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69528. return;
  69529. }
  69530. var scene = this.getScene();
  69531. if (!scene) {
  69532. return;
  69533. }
  69534. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69535. this._texture = this._getFromCache(this.url, this._noMipmap);
  69536. if (!this._texture) {
  69537. if (this._prefiltered) {
  69538. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69539. }
  69540. else {
  69541. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69542. }
  69543. }
  69544. };
  69545. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69546. return this._textureMatrix;
  69547. };
  69548. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69549. this._textureMatrix = value;
  69550. };
  69551. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69552. var texture = BABYLON.SerializationHelper.Parse(function () {
  69553. var prefiltered = false;
  69554. if (parsedTexture.prefiltered) {
  69555. prefiltered = parsedTexture.prefiltered;
  69556. }
  69557. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69558. }, parsedTexture, scene);
  69559. // Local Cubemaps
  69560. if (parsedTexture.boundingBoxPosition) {
  69561. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69562. }
  69563. if (parsedTexture.boundingBoxSize) {
  69564. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69565. }
  69566. // Animations
  69567. if (parsedTexture.animations) {
  69568. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69569. var parsedAnimation = parsedTexture.animations[animationIndex];
  69570. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69571. }
  69572. }
  69573. return texture;
  69574. };
  69575. CubeTexture.prototype.clone = function () {
  69576. var _this = this;
  69577. return BABYLON.SerializationHelper.Clone(function () {
  69578. var scene = _this.getScene();
  69579. if (!scene) {
  69580. return _this;
  69581. }
  69582. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69583. }, this);
  69584. };
  69585. __decorate([
  69586. BABYLON.serialize("rotationY")
  69587. ], CubeTexture.prototype, "rotationY", null);
  69588. return CubeTexture;
  69589. }(BABYLON.BaseTexture));
  69590. BABYLON.CubeTexture = CubeTexture;
  69591. })(BABYLON || (BABYLON = {}));
  69592. //# sourceMappingURL=babylon.cubeTexture.js.map
  69593. var BABYLON;
  69594. (function (BABYLON) {
  69595. /**
  69596. * Raw cube texture where the raw buffers are passed in
  69597. */
  69598. var RawCubeTexture = /** @class */ (function (_super) {
  69599. __extends(RawCubeTexture, _super);
  69600. /**
  69601. * Creates a cube texture where the raw buffers are passed in.
  69602. * @param scene defines the scene the texture is attached to
  69603. * @param data defines the array of data to use to create each face
  69604. * @param size defines the size of the textures
  69605. * @param format defines the format of the data
  69606. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69607. * @param generateMipMaps defines if the engine should generate the mip levels
  69608. * @param invertY defines if data must be stored with Y axis inverted
  69609. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69610. * @param compression defines the compression used (null by default)
  69611. */
  69612. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69613. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69614. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69615. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69616. if (invertY === void 0) { invertY = false; }
  69617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69618. if (compression === void 0) { compression = null; }
  69619. var _this = _super.call(this, "", scene) || this;
  69620. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69621. return _this;
  69622. }
  69623. /**
  69624. * Updates the raw cube texture.
  69625. * @param data defines the data to store
  69626. * @param format defines the data format
  69627. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69628. * @param invertY defines if data must be stored with Y axis inverted
  69629. * @param compression defines the compression used (null by default)
  69630. * @param level defines which level of the texture to update
  69631. */
  69632. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69633. if (compression === void 0) { compression = null; }
  69634. if (level === void 0) { level = 0; }
  69635. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69636. };
  69637. /**
  69638. * Updates a raw cube texture with RGBD encoded data.
  69639. * @param data defines the array of data [mipmap][face] to use to create each face
  69640. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69641. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69642. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69643. * @returns a promsie that resolves when the operation is complete
  69644. */
  69645. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69646. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69647. if (lodScale === void 0) { lodScale = 0.8; }
  69648. if (lodOffset === void 0) { lodOffset = 0; }
  69649. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69650. };
  69651. /**
  69652. * Clones the raw cube texture.
  69653. * @return a new cube texture
  69654. */
  69655. RawCubeTexture.prototype.clone = function () {
  69656. var _this = this;
  69657. return BABYLON.SerializationHelper.Clone(function () {
  69658. var scene = _this.getScene();
  69659. var internalTexture = _this._texture;
  69660. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69661. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69662. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69663. }
  69664. return texture;
  69665. }, this);
  69666. };
  69667. /** @hidden */
  69668. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69669. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69670. internalTexture._bufferViewArrayArray = data;
  69671. internalTexture._lodGenerationScale = lodScale;
  69672. internalTexture._lodGenerationOffset = lodOffset;
  69673. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69674. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69675. internalTexture.isReady = true;
  69676. });
  69677. };
  69678. return RawCubeTexture;
  69679. }(BABYLON.CubeTexture));
  69680. BABYLON.RawCubeTexture = RawCubeTexture;
  69681. })(BABYLON || (BABYLON = {}));
  69682. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69683. var BABYLON;
  69684. (function (BABYLON) {
  69685. var RenderTargetTexture = /** @class */ (function (_super) {
  69686. __extends(RenderTargetTexture, _super);
  69687. /**
  69688. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69689. * or used a shadow, depth texture...
  69690. * @param name The friendly name of the texture
  69691. * @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)
  69692. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69693. * @param generateMipMaps True if mip maps need to be generated after render.
  69694. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69695. * @param type The type of the buffer in the RTT (int, half float, float...)
  69696. * @param isCube True if a cube texture needs to be created
  69697. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69698. * @param generateDepthBuffer True to generate a depth buffer
  69699. * @param generateStencilBuffer True to generate a stencil buffer
  69700. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69701. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69702. */
  69703. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69704. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69705. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69706. if (isCube === void 0) { isCube = false; }
  69707. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69708. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69709. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69710. if (isMulti === void 0) { isMulti = false; }
  69711. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69712. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69713. _this.isCube = isCube;
  69714. _this.renderParticles = true;
  69715. _this.renderSprites = false;
  69716. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69717. _this.ignoreCameraViewport = false;
  69718. // Events
  69719. /**
  69720. * An event triggered when the texture is unbind.
  69721. */
  69722. _this.onBeforeBindObservable = new BABYLON.Observable();
  69723. /**
  69724. * An event triggered when the texture is unbind.
  69725. */
  69726. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69727. /**
  69728. * An event triggered before rendering the texture
  69729. */
  69730. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69731. /**
  69732. * An event triggered after rendering the texture
  69733. */
  69734. _this.onAfterRenderObservable = new BABYLON.Observable();
  69735. /**
  69736. * An event triggered after the texture clear
  69737. */
  69738. _this.onClearObservable = new BABYLON.Observable();
  69739. _this._currentRefreshId = -1;
  69740. _this._refreshRate = 1;
  69741. _this._samples = 1;
  69742. /**
  69743. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69744. * It must define where the camera used to render the texture is set
  69745. */
  69746. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69747. scene = _this.getScene();
  69748. if (!scene) {
  69749. return _this;
  69750. }
  69751. _this.renderList = new Array();
  69752. _this._engine = scene.getEngine();
  69753. _this.name = name;
  69754. _this.isRenderTarget = true;
  69755. _this._initialSizeParameter = size;
  69756. _this._processSizeParameter(size);
  69757. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69758. });
  69759. _this._generateMipMaps = generateMipMaps ? true : false;
  69760. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69761. // Rendering groups
  69762. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69763. _this._renderingManager._useSceneAutoClearSetup = true;
  69764. if (isMulti) {
  69765. return _this;
  69766. }
  69767. _this._renderTargetOptions = {
  69768. generateMipMaps: generateMipMaps,
  69769. type: type,
  69770. format: format,
  69771. samplingMode: samplingMode,
  69772. generateDepthBuffer: generateDepthBuffer,
  69773. generateStencilBuffer: generateStencilBuffer
  69774. };
  69775. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69776. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69777. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69778. }
  69779. if (isCube) {
  69780. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69781. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69782. _this._textureMatrix = BABYLON.Matrix.Identity();
  69783. }
  69784. else {
  69785. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69786. }
  69787. return _this;
  69788. }
  69789. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69790. get: function () {
  69791. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69792. },
  69793. enumerable: true,
  69794. configurable: true
  69795. });
  69796. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69797. get: function () {
  69798. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69799. },
  69800. enumerable: true,
  69801. configurable: true
  69802. });
  69803. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69804. get: function () {
  69805. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69806. },
  69807. enumerable: true,
  69808. configurable: true
  69809. });
  69810. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69811. /**
  69812. * Use this list to define the list of mesh you want to render.
  69813. */
  69814. get: function () {
  69815. return this._renderList;
  69816. },
  69817. set: function (value) {
  69818. this._renderList = value;
  69819. if (this._renderList) {
  69820. this._hookArray(this._renderList);
  69821. }
  69822. },
  69823. enumerable: true,
  69824. configurable: true
  69825. });
  69826. RenderTargetTexture.prototype._hookArray = function (array) {
  69827. var _this = this;
  69828. var oldPush = array.push;
  69829. array.push = function () {
  69830. var items = [];
  69831. for (var _i = 0; _i < arguments.length; _i++) {
  69832. items[_i] = arguments[_i];
  69833. }
  69834. var result = oldPush.apply(array, items);
  69835. _this.getScene().meshes.forEach(function (mesh) {
  69836. mesh._markSubMeshesAsLightDirty();
  69837. });
  69838. return result;
  69839. };
  69840. var oldSplice = array.splice;
  69841. array.splice = function (index, deleteCount) {
  69842. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69843. _this.getScene().meshes.forEach(function (mesh) {
  69844. mesh._markSubMeshesAsLightDirty();
  69845. });
  69846. return deleted;
  69847. };
  69848. };
  69849. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69850. set: function (callback) {
  69851. if (this._onAfterUnbindObserver) {
  69852. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69853. }
  69854. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69855. },
  69856. enumerable: true,
  69857. configurable: true
  69858. });
  69859. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69860. set: function (callback) {
  69861. if (this._onBeforeRenderObserver) {
  69862. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69863. }
  69864. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69865. },
  69866. enumerable: true,
  69867. configurable: true
  69868. });
  69869. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69870. set: function (callback) {
  69871. if (this._onAfterRenderObserver) {
  69872. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69873. }
  69874. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69875. },
  69876. enumerable: true,
  69877. configurable: true
  69878. });
  69879. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69880. set: function (callback) {
  69881. if (this._onClearObserver) {
  69882. this.onClearObservable.remove(this._onClearObserver);
  69883. }
  69884. this._onClearObserver = this.onClearObservable.add(callback);
  69885. },
  69886. enumerable: true,
  69887. configurable: true
  69888. });
  69889. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69890. get: function () {
  69891. return this._renderTargetOptions;
  69892. },
  69893. enumerable: true,
  69894. configurable: true
  69895. });
  69896. RenderTargetTexture.prototype._onRatioRescale = function () {
  69897. if (this._sizeRatio) {
  69898. this.resize(this._initialSizeParameter);
  69899. }
  69900. };
  69901. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69902. get: function () {
  69903. return this._boundingBoxSize;
  69904. },
  69905. /**
  69906. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69907. * When defined, the cubemap will switch to local mode
  69908. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69909. * @example https://www.babylonjs-playground.com/#RNASML
  69910. */
  69911. set: function (value) {
  69912. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69913. return;
  69914. }
  69915. this._boundingBoxSize = value;
  69916. var scene = this.getScene();
  69917. if (scene) {
  69918. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69919. }
  69920. },
  69921. enumerable: true,
  69922. configurable: true
  69923. });
  69924. /**
  69925. * Creates a depth stencil texture.
  69926. * This is only available in WebGL 2 or with the depth texture extension available.
  69927. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69928. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69929. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69930. */
  69931. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69932. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69933. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69934. if (generateStencil === void 0) { generateStencil = false; }
  69935. if (!this.getScene()) {
  69936. return;
  69937. }
  69938. var engine = this.getScene().getEngine();
  69939. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69940. bilinearFiltering: bilinearFiltering,
  69941. comparisonFunction: comparisonFunction,
  69942. generateStencil: generateStencil,
  69943. isCube: this.isCube
  69944. });
  69945. engine.setFrameBufferDepthStencilTexture(this);
  69946. };
  69947. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69948. if (size.ratio) {
  69949. this._sizeRatio = size.ratio;
  69950. this._size = {
  69951. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69952. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69953. };
  69954. }
  69955. else {
  69956. this._size = size;
  69957. }
  69958. };
  69959. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69960. get: function () {
  69961. return this._samples;
  69962. },
  69963. set: function (value) {
  69964. if (this._samples === value) {
  69965. return;
  69966. }
  69967. var scene = this.getScene();
  69968. if (!scene) {
  69969. return;
  69970. }
  69971. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69972. },
  69973. enumerable: true,
  69974. configurable: true
  69975. });
  69976. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  69977. this._currentRefreshId = -1;
  69978. };
  69979. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  69980. get: function () {
  69981. return this._refreshRate;
  69982. },
  69983. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69984. set: function (value) {
  69985. this._refreshRate = value;
  69986. this.resetRefreshCounter();
  69987. },
  69988. enumerable: true,
  69989. configurable: true
  69990. });
  69991. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  69992. if (!this._postProcessManager) {
  69993. var scene = this.getScene();
  69994. if (!scene) {
  69995. return;
  69996. }
  69997. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  69998. this._postProcesses = new Array();
  69999. }
  70000. this._postProcesses.push(postProcess);
  70001. this._postProcesses[0].autoClear = false;
  70002. };
  70003. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70004. if (!this._postProcesses) {
  70005. return;
  70006. }
  70007. if (dispose) {
  70008. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70009. var postProcess = _a[_i];
  70010. postProcess.dispose();
  70011. }
  70012. }
  70013. this._postProcesses = [];
  70014. };
  70015. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70016. if (!this._postProcesses) {
  70017. return;
  70018. }
  70019. var index = this._postProcesses.indexOf(postProcess);
  70020. if (index === -1) {
  70021. return;
  70022. }
  70023. this._postProcesses.splice(index, 1);
  70024. if (this._postProcesses.length > 0) {
  70025. this._postProcesses[0].autoClear = false;
  70026. }
  70027. };
  70028. /** @hidden */
  70029. RenderTargetTexture.prototype._shouldRender = function () {
  70030. if (this._currentRefreshId === -1) { // At least render once
  70031. this._currentRefreshId = 1;
  70032. return true;
  70033. }
  70034. if (this.refreshRate === this._currentRefreshId) {
  70035. this._currentRefreshId = 1;
  70036. return true;
  70037. }
  70038. this._currentRefreshId++;
  70039. return false;
  70040. };
  70041. RenderTargetTexture.prototype.getRenderSize = function () {
  70042. if (this._size.width) {
  70043. return this._size.width;
  70044. }
  70045. return this._size;
  70046. };
  70047. RenderTargetTexture.prototype.getRenderWidth = function () {
  70048. if (this._size.width) {
  70049. return this._size.width;
  70050. }
  70051. return this._size;
  70052. };
  70053. RenderTargetTexture.prototype.getRenderHeight = function () {
  70054. if (this._size.width) {
  70055. return this._size.height;
  70056. }
  70057. return this._size;
  70058. };
  70059. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  70060. get: function () {
  70061. return true;
  70062. },
  70063. enumerable: true,
  70064. configurable: true
  70065. });
  70066. RenderTargetTexture.prototype.scale = function (ratio) {
  70067. var newSize = this.getRenderSize() * ratio;
  70068. this.resize(newSize);
  70069. };
  70070. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  70071. if (this.isCube) {
  70072. return this._textureMatrix;
  70073. }
  70074. return _super.prototype.getReflectionTextureMatrix.call(this);
  70075. };
  70076. RenderTargetTexture.prototype.resize = function (size) {
  70077. this.releaseInternalTexture();
  70078. var scene = this.getScene();
  70079. if (!scene) {
  70080. return;
  70081. }
  70082. this._processSizeParameter(size);
  70083. if (this.isCube) {
  70084. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  70085. }
  70086. else {
  70087. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  70088. }
  70089. };
  70090. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  70091. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  70092. if (dumpForDebug === void 0) { dumpForDebug = false; }
  70093. var scene = this.getScene();
  70094. if (!scene) {
  70095. return;
  70096. }
  70097. var engine = scene.getEngine();
  70098. if (this.useCameraPostProcesses !== undefined) {
  70099. useCameraPostProcess = this.useCameraPostProcesses;
  70100. }
  70101. if (this._waitingRenderList) {
  70102. this.renderList = [];
  70103. for (var index = 0; index < this._waitingRenderList.length; index++) {
  70104. var id = this._waitingRenderList[index];
  70105. var mesh_1 = scene.getMeshByID(id);
  70106. if (mesh_1) {
  70107. this.renderList.push(mesh_1);
  70108. }
  70109. }
  70110. delete this._waitingRenderList;
  70111. }
  70112. // Is predicate defined?
  70113. if (this.renderListPredicate) {
  70114. if (this.renderList) {
  70115. this.renderList.splice(0); // Clear previous renderList
  70116. }
  70117. else {
  70118. this.renderList = [];
  70119. }
  70120. var scene = this.getScene();
  70121. if (!scene) {
  70122. return;
  70123. }
  70124. var sceneMeshes = scene.meshes;
  70125. for (var index = 0; index < sceneMeshes.length; index++) {
  70126. var mesh = sceneMeshes[index];
  70127. if (this.renderListPredicate(mesh)) {
  70128. this.renderList.push(mesh);
  70129. }
  70130. }
  70131. }
  70132. this.onBeforeBindObservable.notifyObservers(this);
  70133. // Set custom projection.
  70134. // Needs to be before binding to prevent changing the aspect ratio.
  70135. var camera;
  70136. if (this.activeCamera) {
  70137. camera = this.activeCamera;
  70138. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70139. if (this.activeCamera !== scene.activeCamera) {
  70140. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  70141. }
  70142. }
  70143. else {
  70144. camera = scene.activeCamera;
  70145. if (camera) {
  70146. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70147. }
  70148. }
  70149. // Prepare renderingManager
  70150. this._renderingManager.reset();
  70151. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  70152. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  70153. var sceneRenderId = scene.getRenderId();
  70154. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  70155. var mesh = currentRenderList[meshIndex];
  70156. if (mesh) {
  70157. if (!mesh.isReady(this.refreshRate === 0)) {
  70158. this.resetRefreshCounter();
  70159. continue;
  70160. }
  70161. mesh._preActivateForIntermediateRendering(sceneRenderId);
  70162. var isMasked = void 0;
  70163. if (!this.renderList && camera) {
  70164. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  70165. }
  70166. else {
  70167. isMasked = false;
  70168. }
  70169. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  70170. mesh._activate(sceneRenderId);
  70171. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  70172. var subMesh = mesh.subMeshes[subIndex];
  70173. scene._activeIndices.addCount(subMesh.indexCount, false);
  70174. this._renderingManager.dispatch(subMesh, mesh);
  70175. }
  70176. }
  70177. }
  70178. }
  70179. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  70180. var particleSystem = scene.particleSystems[particleIndex];
  70181. var emitter = particleSystem.emitter;
  70182. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  70183. continue;
  70184. }
  70185. if (currentRenderList.indexOf(emitter) >= 0) {
  70186. this._renderingManager.dispatchParticles(particleSystem);
  70187. }
  70188. }
  70189. if (this.isCube) {
  70190. for (var face = 0; face < 6; face++) {
  70191. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70192. scene.incrementRenderId();
  70193. scene.resetCachedMaterial();
  70194. }
  70195. }
  70196. else {
  70197. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70198. }
  70199. this.onAfterUnbindObservable.notifyObservers(this);
  70200. if (scene.activeCamera) {
  70201. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  70202. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  70203. }
  70204. engine.setViewport(scene.activeCamera.viewport);
  70205. }
  70206. scene.resetCachedMaterial();
  70207. };
  70208. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  70209. var minimum = 128;
  70210. var x = renderDimension * scale;
  70211. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  70212. // Ensure we don't exceed the render dimension (while staying POT)
  70213. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  70214. };
  70215. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70216. var _this = this;
  70217. if (!this._texture) {
  70218. return;
  70219. }
  70220. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  70221. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70222. });
  70223. };
  70224. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  70225. var scene = this.getScene();
  70226. if (!scene) {
  70227. return;
  70228. }
  70229. var engine = scene.getEngine();
  70230. if (!this._texture) {
  70231. return;
  70232. }
  70233. // Bind
  70234. if (this._postProcessManager) {
  70235. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  70236. }
  70237. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  70238. if (this._texture) {
  70239. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  70240. }
  70241. }
  70242. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  70243. // Clear
  70244. if (this.onClearObservable.hasObservers()) {
  70245. this.onClearObservable.notifyObservers(engine);
  70246. }
  70247. else {
  70248. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  70249. }
  70250. if (!this._doNotChangeAspectRatio) {
  70251. scene.updateTransformMatrix(true);
  70252. }
  70253. // Render
  70254. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  70255. if (this._postProcessManager) {
  70256. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  70257. }
  70258. else if (useCameraPostProcess) {
  70259. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  70260. }
  70261. if (!this._doNotChangeAspectRatio) {
  70262. scene.updateTransformMatrix(true);
  70263. }
  70264. // Dump ?
  70265. if (dumpForDebug) {
  70266. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  70267. }
  70268. // Unbind
  70269. if (!this.isCube || faceIndex === 5) {
  70270. if (this.isCube) {
  70271. if (faceIndex === 5) {
  70272. engine.generateMipMapsForCubemap(this._texture);
  70273. }
  70274. }
  70275. this.unbindFrameBuffer(engine, faceIndex);
  70276. }
  70277. else {
  70278. this.onAfterRenderObservable.notifyObservers(faceIndex);
  70279. }
  70280. };
  70281. /**
  70282. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  70283. * This allowed control for front to back rendering or reversly depending of the special needs.
  70284. *
  70285. * @param renderingGroupId The rendering group id corresponding to its index
  70286. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  70287. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70288. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70289. */
  70290. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70291. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70292. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70293. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70294. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70295. };
  70296. /**
  70297. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70298. *
  70299. * @param renderingGroupId The rendering group id corresponding to its index
  70300. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70301. */
  70302. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70303. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70304. this._renderingManager._useSceneAutoClearSetup = false;
  70305. };
  70306. RenderTargetTexture.prototype.clone = function () {
  70307. var textureSize = this.getSize();
  70308. 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);
  70309. // Base texture
  70310. newTexture.hasAlpha = this.hasAlpha;
  70311. newTexture.level = this.level;
  70312. // RenderTarget Texture
  70313. newTexture.coordinatesMode = this.coordinatesMode;
  70314. if (this.renderList) {
  70315. newTexture.renderList = this.renderList.slice(0);
  70316. }
  70317. return newTexture;
  70318. };
  70319. RenderTargetTexture.prototype.serialize = function () {
  70320. if (!this.name) {
  70321. return null;
  70322. }
  70323. var serializationObject = _super.prototype.serialize.call(this);
  70324. serializationObject.renderTargetSize = this.getRenderSize();
  70325. serializationObject.renderList = [];
  70326. if (this.renderList) {
  70327. for (var index = 0; index < this.renderList.length; index++) {
  70328. serializationObject.renderList.push(this.renderList[index].id);
  70329. }
  70330. }
  70331. return serializationObject;
  70332. };
  70333. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70334. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70335. var objBuffer = this.getInternalTexture();
  70336. var scene = this.getScene();
  70337. if (objBuffer && scene) {
  70338. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70339. }
  70340. };
  70341. RenderTargetTexture.prototype.dispose = function () {
  70342. if (this._postProcessManager) {
  70343. this._postProcessManager.dispose();
  70344. this._postProcessManager = null;
  70345. }
  70346. this.clearPostProcesses(true);
  70347. if (this._resizeObserver) {
  70348. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70349. this._resizeObserver = null;
  70350. }
  70351. this.renderList = null;
  70352. // Remove from custom render targets
  70353. var scene = this.getScene();
  70354. if (!scene) {
  70355. return;
  70356. }
  70357. var index = scene.customRenderTargets.indexOf(this);
  70358. if (index >= 0) {
  70359. scene.customRenderTargets.splice(index, 1);
  70360. }
  70361. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70362. var camera = _a[_i];
  70363. index = camera.customRenderTargets.indexOf(this);
  70364. if (index >= 0) {
  70365. camera.customRenderTargets.splice(index, 1);
  70366. }
  70367. }
  70368. _super.prototype.dispose.call(this);
  70369. };
  70370. /** @hidden */
  70371. RenderTargetTexture.prototype._rebuild = function () {
  70372. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70373. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70374. }
  70375. if (this._postProcessManager) {
  70376. this._postProcessManager._rebuild();
  70377. }
  70378. };
  70379. /**
  70380. * Clear the info related to rendering groups preventing retention point in material dispose.
  70381. */
  70382. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70383. if (this._renderingManager) {
  70384. this._renderingManager.freeRenderingGroups();
  70385. }
  70386. };
  70387. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70388. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70389. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70390. return RenderTargetTexture;
  70391. }(BABYLON.Texture));
  70392. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70393. })(BABYLON || (BABYLON = {}));
  70394. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70395. var BABYLON;
  70396. (function (BABYLON) {
  70397. ;
  70398. var MultiRenderTarget = /** @class */ (function (_super) {
  70399. __extends(MultiRenderTarget, _super);
  70400. function MultiRenderTarget(name, size, count, scene, options) {
  70401. var _this = this;
  70402. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70403. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70404. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70405. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70406. _this._engine = scene.getEngine();
  70407. if (!_this.isSupported) {
  70408. _this.dispose();
  70409. return;
  70410. }
  70411. var types = [];
  70412. var samplingModes = [];
  70413. for (var i = 0; i < count; i++) {
  70414. if (options && options.types && options.types[i] !== undefined) {
  70415. types.push(options.types[i]);
  70416. }
  70417. else {
  70418. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70419. }
  70420. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70421. samplingModes.push(options.samplingModes[i]);
  70422. }
  70423. else {
  70424. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70425. }
  70426. }
  70427. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70428. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70429. _this._size = size;
  70430. _this._multiRenderTargetOptions = {
  70431. samplingModes: samplingModes,
  70432. generateMipMaps: generateMipMaps,
  70433. generateDepthBuffer: generateDepthBuffer,
  70434. generateStencilBuffer: generateStencilBuffer,
  70435. generateDepthTexture: generateDepthTexture,
  70436. types: types,
  70437. textureCount: count
  70438. };
  70439. _this._createInternalTextures();
  70440. _this._createTextures();
  70441. return _this;
  70442. }
  70443. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70444. get: function () {
  70445. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70446. },
  70447. enumerable: true,
  70448. configurable: true
  70449. });
  70450. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70451. get: function () {
  70452. return this._textures;
  70453. },
  70454. enumerable: true,
  70455. configurable: true
  70456. });
  70457. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70458. get: function () {
  70459. return this._textures[this._textures.length - 1];
  70460. },
  70461. enumerable: true,
  70462. configurable: true
  70463. });
  70464. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70465. set: function (wrap) {
  70466. if (this._textures) {
  70467. for (var i = 0; i < this._textures.length; i++) {
  70468. this._textures[i].wrapU = wrap;
  70469. }
  70470. }
  70471. },
  70472. enumerable: true,
  70473. configurable: true
  70474. });
  70475. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70476. set: function (wrap) {
  70477. if (this._textures) {
  70478. for (var i = 0; i < this._textures.length; i++) {
  70479. this._textures[i].wrapV = wrap;
  70480. }
  70481. }
  70482. },
  70483. enumerable: true,
  70484. configurable: true
  70485. });
  70486. /** @hidden */
  70487. MultiRenderTarget.prototype._rebuild = function () {
  70488. this.releaseInternalTextures();
  70489. this._createInternalTextures();
  70490. for (var i = 0; i < this._internalTextures.length; i++) {
  70491. var texture = this._textures[i];
  70492. texture._texture = this._internalTextures[i];
  70493. }
  70494. // Keeps references to frame buffer and stencil/depth buffer
  70495. this._texture = this._internalTextures[0];
  70496. };
  70497. MultiRenderTarget.prototype._createInternalTextures = function () {
  70498. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70499. };
  70500. MultiRenderTarget.prototype._createTextures = function () {
  70501. this._textures = [];
  70502. for (var i = 0; i < this._internalTextures.length; i++) {
  70503. var texture = new BABYLON.Texture(null, this.getScene());
  70504. texture._texture = this._internalTextures[i];
  70505. this._textures.push(texture);
  70506. }
  70507. // Keeps references to frame buffer and stencil/depth buffer
  70508. this._texture = this._internalTextures[0];
  70509. };
  70510. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70511. get: function () {
  70512. return this._samples;
  70513. },
  70514. set: function (value) {
  70515. if (this._samples === value) {
  70516. return;
  70517. }
  70518. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70519. },
  70520. enumerable: true,
  70521. configurable: true
  70522. });
  70523. MultiRenderTarget.prototype.resize = function (size) {
  70524. this.releaseInternalTextures();
  70525. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70526. this._createInternalTextures();
  70527. };
  70528. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70529. var _this = this;
  70530. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70531. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70532. });
  70533. };
  70534. MultiRenderTarget.prototype.dispose = function () {
  70535. this.releaseInternalTextures();
  70536. _super.prototype.dispose.call(this);
  70537. };
  70538. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70539. if (!this._internalTextures) {
  70540. return;
  70541. }
  70542. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70543. if (this._internalTextures[i] !== undefined) {
  70544. this._internalTextures[i].dispose();
  70545. this._internalTextures.splice(i, 1);
  70546. }
  70547. }
  70548. };
  70549. return MultiRenderTarget;
  70550. }(BABYLON.RenderTargetTexture));
  70551. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70552. })(BABYLON || (BABYLON = {}));
  70553. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70554. var BABYLON;
  70555. (function (BABYLON) {
  70556. var MirrorTexture = /** @class */ (function (_super) {
  70557. __extends(MirrorTexture, _super);
  70558. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70559. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70561. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70562. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70563. _this.scene = scene;
  70564. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70565. _this._transformMatrix = BABYLON.Matrix.Zero();
  70566. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70567. _this._adaptiveBlurKernel = 0;
  70568. _this._blurKernelX = 0;
  70569. _this._blurKernelY = 0;
  70570. _this._blurRatio = 1.0;
  70571. _this.ignoreCameraViewport = true;
  70572. _this._updateGammaSpace();
  70573. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70574. _this._updateGammaSpace;
  70575. });
  70576. _this.onBeforeRenderObservable.add(function () {
  70577. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70578. _this._savedViewMatrix = scene.getViewMatrix();
  70579. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70580. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70581. scene.clipPlane = _this.mirrorPlane;
  70582. scene.getEngine().cullBackFaces = false;
  70583. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70584. });
  70585. _this.onAfterRenderObservable.add(function () {
  70586. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70587. scene.getEngine().cullBackFaces = true;
  70588. scene._mirroredCameraPosition = null;
  70589. delete scene.clipPlane;
  70590. });
  70591. return _this;
  70592. }
  70593. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70594. get: function () {
  70595. return this._blurRatio;
  70596. },
  70597. set: function (value) {
  70598. if (this._blurRatio === value) {
  70599. return;
  70600. }
  70601. this._blurRatio = value;
  70602. this._preparePostProcesses();
  70603. },
  70604. enumerable: true,
  70605. configurable: true
  70606. });
  70607. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70608. set: function (value) {
  70609. this._adaptiveBlurKernel = value;
  70610. this._autoComputeBlurKernel();
  70611. },
  70612. enumerable: true,
  70613. configurable: true
  70614. });
  70615. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70616. set: function (value) {
  70617. this.blurKernelX = value;
  70618. this.blurKernelY = value;
  70619. },
  70620. enumerable: true,
  70621. configurable: true
  70622. });
  70623. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70624. get: function () {
  70625. return this._blurKernelX;
  70626. },
  70627. set: function (value) {
  70628. if (this._blurKernelX === value) {
  70629. return;
  70630. }
  70631. this._blurKernelX = value;
  70632. this._preparePostProcesses();
  70633. },
  70634. enumerable: true,
  70635. configurable: true
  70636. });
  70637. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70638. get: function () {
  70639. return this._blurKernelY;
  70640. },
  70641. set: function (value) {
  70642. if (this._blurKernelY === value) {
  70643. return;
  70644. }
  70645. this._blurKernelY = value;
  70646. this._preparePostProcesses();
  70647. },
  70648. enumerable: true,
  70649. configurable: true
  70650. });
  70651. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70652. var engine = this.getScene().getEngine();
  70653. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70654. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70655. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70656. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70657. };
  70658. MirrorTexture.prototype._onRatioRescale = function () {
  70659. if (this._sizeRatio) {
  70660. this.resize(this._initialSizeParameter);
  70661. if (!this._adaptiveBlurKernel) {
  70662. this._preparePostProcesses();
  70663. }
  70664. }
  70665. if (this._adaptiveBlurKernel) {
  70666. this._autoComputeBlurKernel();
  70667. }
  70668. };
  70669. MirrorTexture.prototype._updateGammaSpace = function () {
  70670. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70671. };
  70672. MirrorTexture.prototype._preparePostProcesses = function () {
  70673. this.clearPostProcesses(true);
  70674. if (this._blurKernelX && this._blurKernelY) {
  70675. var engine = this.getScene().getEngine();
  70676. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70677. 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);
  70678. this._blurX.autoClear = false;
  70679. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70680. this._blurX.inputTexture = this._texture;
  70681. }
  70682. else {
  70683. this._blurX.alwaysForcePOT = true;
  70684. }
  70685. 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);
  70686. this._blurY.autoClear = false;
  70687. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70688. this.addPostProcess(this._blurX);
  70689. this.addPostProcess(this._blurY);
  70690. }
  70691. else {
  70692. if (this._blurY) {
  70693. this.removePostProcess(this._blurY);
  70694. this._blurY.dispose();
  70695. this._blurY = null;
  70696. }
  70697. if (this._blurX) {
  70698. this.removePostProcess(this._blurX);
  70699. this._blurX.dispose();
  70700. this._blurX = null;
  70701. }
  70702. }
  70703. };
  70704. MirrorTexture.prototype.clone = function () {
  70705. var scene = this.getScene();
  70706. if (!scene) {
  70707. return this;
  70708. }
  70709. var textureSize = this.getSize();
  70710. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70711. // Base texture
  70712. newTexture.hasAlpha = this.hasAlpha;
  70713. newTexture.level = this.level;
  70714. // Mirror Texture
  70715. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70716. if (this.renderList) {
  70717. newTexture.renderList = this.renderList.slice(0);
  70718. }
  70719. return newTexture;
  70720. };
  70721. MirrorTexture.prototype.serialize = function () {
  70722. if (!this.name) {
  70723. return null;
  70724. }
  70725. var serializationObject = _super.prototype.serialize.call(this);
  70726. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70727. return serializationObject;
  70728. };
  70729. MirrorTexture.prototype.dispose = function () {
  70730. _super.prototype.dispose.call(this);
  70731. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70732. };
  70733. return MirrorTexture;
  70734. }(BABYLON.RenderTargetTexture));
  70735. BABYLON.MirrorTexture = MirrorTexture;
  70736. })(BABYLON || (BABYLON = {}));
  70737. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70738. var BABYLON;
  70739. (function (BABYLON) {
  70740. /**
  70741. * Creates a refraction texture used by refraction channel of the standard material.
  70742. * @param name the texture name
  70743. * @param size size of the underlying texture
  70744. * @param scene root scene
  70745. */
  70746. var RefractionTexture = /** @class */ (function (_super) {
  70747. __extends(RefractionTexture, _super);
  70748. function RefractionTexture(name, size, scene, generateMipMaps) {
  70749. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70750. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70751. _this.depth = 2.0;
  70752. _this.onBeforeRenderObservable.add(function () {
  70753. scene.clipPlane = _this.refractionPlane;
  70754. });
  70755. _this.onAfterRenderObservable.add(function () {
  70756. delete scene.clipPlane;
  70757. });
  70758. return _this;
  70759. }
  70760. RefractionTexture.prototype.clone = function () {
  70761. var scene = this.getScene();
  70762. if (!scene) {
  70763. return this;
  70764. }
  70765. var textureSize = this.getSize();
  70766. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70767. // Base texture
  70768. newTexture.hasAlpha = this.hasAlpha;
  70769. newTexture.level = this.level;
  70770. // Refraction Texture
  70771. newTexture.refractionPlane = this.refractionPlane.clone();
  70772. if (this.renderList) {
  70773. newTexture.renderList = this.renderList.slice(0);
  70774. }
  70775. newTexture.depth = this.depth;
  70776. return newTexture;
  70777. };
  70778. RefractionTexture.prototype.serialize = function () {
  70779. if (!this.name) {
  70780. return null;
  70781. }
  70782. var serializationObject = _super.prototype.serialize.call(this);
  70783. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70784. serializationObject.depth = this.depth;
  70785. return serializationObject;
  70786. };
  70787. return RefractionTexture;
  70788. }(BABYLON.RenderTargetTexture));
  70789. BABYLON.RefractionTexture = RefractionTexture;
  70790. })(BABYLON || (BABYLON = {}));
  70791. //# sourceMappingURL=babylon.refractionTexture.js.map
  70792. var BABYLON;
  70793. (function (BABYLON) {
  70794. /**
  70795. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70796. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70797. */
  70798. var DynamicTexture = /** @class */ (function (_super) {
  70799. __extends(DynamicTexture, _super);
  70800. /**
  70801. * Creates a {BABYLON.DynamicTexture}
  70802. * @param name defines the name of the texture
  70803. * @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
  70804. * @param scene defines the scene where you want the texture
  70805. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70806. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70807. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70808. */
  70809. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70810. if (scene === void 0) { scene = null; }
  70811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70812. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70813. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70814. _this.name = name;
  70815. _this._engine = _this.getScene().getEngine();
  70816. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70817. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70818. _this._generateMipMaps = generateMipMaps;
  70819. if (options.getContext) {
  70820. _this._canvas = options;
  70821. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70822. }
  70823. else {
  70824. _this._canvas = document.createElement("canvas");
  70825. if (options.width || options.width === 0) {
  70826. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70827. }
  70828. else {
  70829. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70830. }
  70831. }
  70832. var textureSize = _this.getSize();
  70833. _this._canvas.width = textureSize.width;
  70834. _this._canvas.height = textureSize.height;
  70835. _this._context = _this._canvas.getContext("2d");
  70836. return _this;
  70837. }
  70838. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70839. /**
  70840. * Gets the current state of canRescale
  70841. */
  70842. get: function () {
  70843. return true;
  70844. },
  70845. enumerable: true,
  70846. configurable: true
  70847. });
  70848. DynamicTexture.prototype._recreate = function (textureSize) {
  70849. this._canvas.width = textureSize.width;
  70850. this._canvas.height = textureSize.height;
  70851. this.releaseInternalTexture();
  70852. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70853. };
  70854. /**
  70855. * Scales the texture
  70856. * @param ratio the scale factor to apply to both width and height
  70857. */
  70858. DynamicTexture.prototype.scale = function (ratio) {
  70859. var textureSize = this.getSize();
  70860. textureSize.width *= ratio;
  70861. textureSize.height *= ratio;
  70862. this._recreate(textureSize);
  70863. };
  70864. /**
  70865. * Resizes the texture
  70866. * @param width the new width
  70867. * @param height the new height
  70868. */
  70869. DynamicTexture.prototype.scaleTo = function (width, height) {
  70870. var textureSize = this.getSize();
  70871. textureSize.width = width;
  70872. textureSize.height = height;
  70873. this._recreate(textureSize);
  70874. };
  70875. /**
  70876. * Gets the context of the canvas used by the texture
  70877. * @returns the canvas context of the dynamic texture
  70878. */
  70879. DynamicTexture.prototype.getContext = function () {
  70880. return this._context;
  70881. };
  70882. /**
  70883. * Clears the texture
  70884. */
  70885. DynamicTexture.prototype.clear = function () {
  70886. var size = this.getSize();
  70887. this._context.fillRect(0, 0, size.width, size.height);
  70888. };
  70889. /**
  70890. * Updates the texture
  70891. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70892. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70893. */
  70894. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70895. if (premulAlpha === void 0) { premulAlpha = false; }
  70896. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70897. };
  70898. /**
  70899. * Draws text onto the texture
  70900. * @param text defines the text to be drawn
  70901. * @param x defines the placement of the text from the left
  70902. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70903. * @param font defines the font to be used with font-style, font-size, font-name
  70904. * @param color defines the color used for the text
  70905. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70906. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70907. * @param update defines whether texture is immediately update (default is true)
  70908. */
  70909. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70910. if (update === void 0) { update = true; }
  70911. var size = this.getSize();
  70912. if (clearColor) {
  70913. this._context.fillStyle = clearColor;
  70914. this._context.fillRect(0, 0, size.width, size.height);
  70915. }
  70916. this._context.font = font;
  70917. if (x === null || x === undefined) {
  70918. var textSize = this._context.measureText(text);
  70919. x = (size.width - textSize.width) / 2;
  70920. }
  70921. if (y === null || y === undefined) {
  70922. var fontSize = parseInt((font.replace(/\D/g, '')));
  70923. y = (size.height / 2) + (fontSize / 3.65);
  70924. }
  70925. this._context.fillStyle = color;
  70926. this._context.fillText(text, x, y);
  70927. if (update) {
  70928. this.update(invertY);
  70929. }
  70930. };
  70931. /**
  70932. * Clones the texture
  70933. * @returns the clone of the texture.
  70934. */
  70935. DynamicTexture.prototype.clone = function () {
  70936. var scene = this.getScene();
  70937. if (!scene) {
  70938. return this;
  70939. }
  70940. var textureSize = this.getSize();
  70941. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70942. // Base texture
  70943. newTexture.hasAlpha = this.hasAlpha;
  70944. newTexture.level = this.level;
  70945. // Dynamic Texture
  70946. newTexture.wrapU = this.wrapU;
  70947. newTexture.wrapV = this.wrapV;
  70948. return newTexture;
  70949. };
  70950. /**
  70951. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70952. * @returns a serialized dynamic texture object
  70953. */
  70954. DynamicTexture.prototype.serialize = function () {
  70955. var scene = this.getScene();
  70956. if (scene && !scene.isReady()) {
  70957. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70958. }
  70959. var serializationObject = _super.prototype.serialize.call(this);
  70960. serializationObject.base64String = this._canvas.toDataURL();
  70961. serializationObject.invertY = this._invertY;
  70962. serializationObject.samplingMode = this.samplingMode;
  70963. return serializationObject;
  70964. };
  70965. /** @hidden */
  70966. DynamicTexture.prototype._rebuild = function () {
  70967. this.update();
  70968. };
  70969. return DynamicTexture;
  70970. }(BABYLON.Texture));
  70971. BABYLON.DynamicTexture = DynamicTexture;
  70972. })(BABYLON || (BABYLON = {}));
  70973. //# sourceMappingURL=babylon.dynamicTexture.js.map
  70974. var BABYLON;
  70975. (function (BABYLON) {
  70976. var VideoTexture = /** @class */ (function (_super) {
  70977. __extends(VideoTexture, _super);
  70978. /**
  70979. * Creates a video texture.
  70980. * Sample : https://doc.babylonjs.com/how_to/video_texture
  70981. * @param {string | null} name optional name, will detect from video source, if not defined
  70982. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  70983. * @param {BABYLON.Scene} scene is obviously the current scene.
  70984. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  70985. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  70986. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  70987. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  70988. */
  70989. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  70990. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70991. if (invertY === void 0) { invertY = false; }
  70992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70993. if (settings === void 0) { settings = {
  70994. autoPlay: true,
  70995. loop: true,
  70996. autoUpdateTexture: true,
  70997. }; }
  70998. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70999. _this._onUserActionRequestedObservable = null;
  71000. _this._stillImageCaptured = false;
  71001. _this._poster = false;
  71002. _this._createInternalTexture = function () {
  71003. if (_this._texture != null) {
  71004. if (_this._poster) {
  71005. _this._texture.dispose();
  71006. _this._poster = false;
  71007. }
  71008. else {
  71009. return;
  71010. }
  71011. }
  71012. if (!_this._engine.needPOTTextures ||
  71013. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71014. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71015. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71016. }
  71017. else {
  71018. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71019. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71020. _this._generateMipMaps = false;
  71021. }
  71022. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71023. if (!_this.video.autoplay) {
  71024. var oldHandler_1 = _this.video.onplaying;
  71025. var error_1 = false;
  71026. _this.video.onplaying = function () {
  71027. _this.video.onplaying = oldHandler_1;
  71028. _this._texture.isReady = true;
  71029. _this._updateInternalTexture();
  71030. if (!error_1) {
  71031. _this.video.pause();
  71032. }
  71033. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71034. _this.onLoadObservable.notifyObservers(_this);
  71035. }
  71036. };
  71037. var playing = _this.video.play();
  71038. if (playing) {
  71039. playing.then(function () {
  71040. // Everything is good.
  71041. })
  71042. .catch(function () {
  71043. error_1 = true;
  71044. // On Chrome for instance, new policies might prevent playing without user interaction.
  71045. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  71046. _this._onUserActionRequestedObservable.notifyObservers(_this);
  71047. }
  71048. });
  71049. }
  71050. else {
  71051. _this.video.onplaying = oldHandler_1;
  71052. _this._texture.isReady = true;
  71053. _this._updateInternalTexture();
  71054. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71055. _this.onLoadObservable.notifyObservers(_this);
  71056. }
  71057. }
  71058. }
  71059. else {
  71060. _this._texture.isReady = true;
  71061. _this._updateInternalTexture();
  71062. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71063. _this.onLoadObservable.notifyObservers(_this);
  71064. }
  71065. }
  71066. };
  71067. _this.reset = function () {
  71068. if (_this._texture == null) {
  71069. return;
  71070. }
  71071. if (!_this._poster) {
  71072. _this._texture.dispose();
  71073. _this._texture = null;
  71074. }
  71075. };
  71076. _this._updateInternalTexture = function (e) {
  71077. if (_this._texture == null || !_this._texture.isReady) {
  71078. return;
  71079. }
  71080. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  71081. return;
  71082. }
  71083. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  71084. };
  71085. _this._engine = _this.getScene().getEngine();
  71086. _this._generateMipMaps = generateMipMaps;
  71087. _this._samplingMode = samplingMode;
  71088. _this.autoUpdateTexture = settings.autoUpdateTexture;
  71089. _this.name = name || _this._getName(src);
  71090. _this.video = _this._getVideo(src);
  71091. if (settings.poster) {
  71092. _this.video.poster = settings.poster;
  71093. }
  71094. if (settings.autoPlay !== undefined) {
  71095. _this.video.autoplay = settings.autoPlay;
  71096. }
  71097. if (settings.loop !== undefined) {
  71098. _this.video.loop = settings.loop;
  71099. }
  71100. _this.video.setAttribute("playsinline", "");
  71101. _this.video.addEventListener("canplay", _this._createInternalTexture);
  71102. _this.video.addEventListener("paused", _this._updateInternalTexture);
  71103. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  71104. _this.video.addEventListener("emptied", _this.reset);
  71105. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  71106. _this._createInternalTexture();
  71107. }
  71108. if (settings.poster) {
  71109. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  71110. _this._poster = true;
  71111. }
  71112. return _this;
  71113. }
  71114. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  71115. get: function () {
  71116. if (!this._onUserActionRequestedObservable) {
  71117. this._onUserActionRequestedObservable = new BABYLON.Observable();
  71118. }
  71119. return this._onUserActionRequestedObservable;
  71120. },
  71121. enumerable: true,
  71122. configurable: true
  71123. });
  71124. VideoTexture.prototype._getName = function (src) {
  71125. if (src instanceof HTMLVideoElement) {
  71126. return src.currentSrc;
  71127. }
  71128. if (typeof src === "object") {
  71129. return src.toString();
  71130. }
  71131. return src;
  71132. };
  71133. ;
  71134. VideoTexture.prototype._getVideo = function (src) {
  71135. if (src instanceof HTMLVideoElement) {
  71136. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  71137. return src;
  71138. }
  71139. var video = document.createElement("video");
  71140. if (typeof src === "string") {
  71141. BABYLON.Tools.SetCorsBehavior(src, video);
  71142. video.src = src;
  71143. }
  71144. else {
  71145. BABYLON.Tools.SetCorsBehavior(src[0], video);
  71146. src.forEach(function (url) {
  71147. var source = document.createElement("source");
  71148. source.src = url;
  71149. video.appendChild(source);
  71150. });
  71151. }
  71152. return video;
  71153. };
  71154. ;
  71155. /**
  71156. * @hidden Internal method to initiate `update`.
  71157. */
  71158. VideoTexture.prototype._rebuild = function () {
  71159. this.update();
  71160. };
  71161. /**
  71162. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  71163. */
  71164. VideoTexture.prototype.update = function () {
  71165. if (!this.autoUpdateTexture) {
  71166. // Expecting user to call `updateTexture` manually
  71167. return;
  71168. }
  71169. this.updateTexture(true);
  71170. };
  71171. /**
  71172. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  71173. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  71174. */
  71175. VideoTexture.prototype.updateTexture = function (isVisible) {
  71176. if (!isVisible) {
  71177. return;
  71178. }
  71179. if (this.video.paused && this._stillImageCaptured) {
  71180. return;
  71181. }
  71182. this._stillImageCaptured = true;
  71183. this._updateInternalTexture();
  71184. };
  71185. /**
  71186. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  71187. * @param url New url.
  71188. */
  71189. VideoTexture.prototype.updateURL = function (url) {
  71190. this.video.src = url;
  71191. };
  71192. VideoTexture.prototype.dispose = function () {
  71193. _super.prototype.dispose.call(this);
  71194. if (this._onUserActionRequestedObservable) {
  71195. this._onUserActionRequestedObservable.clear();
  71196. this._onUserActionRequestedObservable = null;
  71197. }
  71198. this.video.removeEventListener("canplay", this._createInternalTexture);
  71199. this.video.removeEventListener("paused", this._updateInternalTexture);
  71200. this.video.removeEventListener("seeked", this._updateInternalTexture);
  71201. this.video.removeEventListener("emptied", this.reset);
  71202. this.video.pause();
  71203. };
  71204. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  71205. var video = document.createElement("video");
  71206. video.setAttribute('autoplay', '');
  71207. video.setAttribute('muted', '');
  71208. video.setAttribute('playsinline', '');
  71209. var constraintsDeviceId;
  71210. if (constraints && constraints.deviceId) {
  71211. constraintsDeviceId = {
  71212. exact: constraints.deviceId,
  71213. };
  71214. }
  71215. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  71216. if (navigator.mediaDevices) {
  71217. navigator.mediaDevices.getUserMedia({ video: constraints })
  71218. .then(function (stream) {
  71219. if (video.mozSrcObject !== undefined) {
  71220. // hack for Firefox < 19
  71221. video.mozSrcObject = stream;
  71222. }
  71223. else {
  71224. video.srcObject = stream;
  71225. }
  71226. var onPlaying = function () {
  71227. if (onReady) {
  71228. onReady(new VideoTexture("video", video, scene, true, true));
  71229. }
  71230. video.removeEventListener("playing", onPlaying);
  71231. };
  71232. video.addEventListener("playing", onPlaying);
  71233. video.play();
  71234. })
  71235. .catch(function (err) {
  71236. BABYLON.Tools.Error(err.name);
  71237. });
  71238. }
  71239. else {
  71240. navigator.getUserMedia =
  71241. navigator.getUserMedia ||
  71242. navigator.webkitGetUserMedia ||
  71243. navigator.mozGetUserMedia ||
  71244. navigator.msGetUserMedia;
  71245. if (navigator.getUserMedia) {
  71246. navigator.getUserMedia({
  71247. video: {
  71248. deviceId: constraintsDeviceId,
  71249. width: {
  71250. min: (constraints && constraints.minWidth) || 256,
  71251. max: (constraints && constraints.maxWidth) || 640,
  71252. },
  71253. height: {
  71254. min: (constraints && constraints.minHeight) || 256,
  71255. max: (constraints && constraints.maxHeight) || 480,
  71256. },
  71257. },
  71258. }, function (stream) {
  71259. if (video.mozSrcObject !== undefined) {
  71260. // hack for Firefox < 19
  71261. video.mozSrcObject = stream;
  71262. }
  71263. else {
  71264. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  71265. }
  71266. video.play();
  71267. if (onReady) {
  71268. onReady(new VideoTexture("video", video, scene, true, true));
  71269. }
  71270. }, function (e) {
  71271. BABYLON.Tools.Error(e.name);
  71272. });
  71273. }
  71274. }
  71275. };
  71276. return VideoTexture;
  71277. }(BABYLON.Texture));
  71278. BABYLON.VideoTexture = VideoTexture;
  71279. })(BABYLON || (BABYLON = {}));
  71280. //# sourceMappingURL=babylon.videoTexture.js.map
  71281. var BABYLON;
  71282. (function (BABYLON) {
  71283. var RawTexture = /** @class */ (function (_super) {
  71284. __extends(RawTexture, _super);
  71285. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  71286. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71287. if (invertY === void 0) { invertY = false; }
  71288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71289. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71290. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71291. _this.format = format;
  71292. _this._engine = scene.getEngine();
  71293. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71294. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71295. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71296. return _this;
  71297. }
  71298. RawTexture.prototype.update = function (data) {
  71299. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71300. };
  71301. // Statics
  71302. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71303. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71304. if (invertY === void 0) { invertY = false; }
  71305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71306. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71307. };
  71308. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71309. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71310. if (invertY === void 0) { invertY = false; }
  71311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71312. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71313. };
  71314. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71315. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71316. if (invertY === void 0) { invertY = false; }
  71317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71318. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71319. };
  71320. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71321. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71322. if (invertY === void 0) { invertY = false; }
  71323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71324. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71325. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71326. };
  71327. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71328. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71329. if (invertY === void 0) { invertY = false; }
  71330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71331. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71332. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71333. };
  71334. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71335. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71336. if (invertY === void 0) { invertY = false; }
  71337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71338. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71339. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71340. };
  71341. return RawTexture;
  71342. }(BABYLON.Texture));
  71343. BABYLON.RawTexture = RawTexture;
  71344. })(BABYLON || (BABYLON = {}));
  71345. //# sourceMappingURL=babylon.rawTexture.js.map
  71346. var BABYLON;
  71347. (function (BABYLON) {
  71348. /**
  71349. * Class used to store 3D textures containing user data
  71350. */
  71351. var RawTexture3D = /** @class */ (function (_super) {
  71352. __extends(RawTexture3D, _super);
  71353. /**
  71354. * Create a new RawTexture3D
  71355. * @param data defines the data of the texture
  71356. * @param width defines the width of the texture
  71357. * @param height defines the height of the texture
  71358. * @param depth defines the depth of the texture
  71359. * @param format defines the texture format to use
  71360. * @param scene defines the hosting scene
  71361. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71362. * @param invertY defines if texture must be stored with Y axis inverted
  71363. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71364. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71365. */
  71366. function RawTexture3D(data, width, height, depth,
  71367. /** Gets or sets the texture format to use */
  71368. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71369. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71370. if (invertY === void 0) { invertY = false; }
  71371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71372. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71373. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71374. _this.format = format;
  71375. _this._engine = scene.getEngine();
  71376. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71377. _this.is3D = true;
  71378. return _this;
  71379. }
  71380. /**
  71381. * Update the texture with new data
  71382. * @param data defines the data to store in the texture
  71383. */
  71384. RawTexture3D.prototype.update = function (data) {
  71385. if (!this._texture) {
  71386. return;
  71387. }
  71388. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71389. };
  71390. return RawTexture3D;
  71391. }(BABYLON.Texture));
  71392. BABYLON.RawTexture3D = RawTexture3D;
  71393. })(BABYLON || (BABYLON = {}));
  71394. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71395. var BABYLON;
  71396. (function (BABYLON) {
  71397. /**
  71398. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71399. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71400. */
  71401. var PostProcessManager = /** @class */ (function () {
  71402. /**
  71403. * Creates a new instance PostProcess
  71404. * @param scene The scene that the post process is associated with.
  71405. */
  71406. function PostProcessManager(scene) {
  71407. this._vertexBuffers = {};
  71408. this._scene = scene;
  71409. }
  71410. PostProcessManager.prototype._prepareBuffers = function () {
  71411. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71412. return;
  71413. }
  71414. // VBO
  71415. var vertices = [];
  71416. vertices.push(1, 1);
  71417. vertices.push(-1, 1);
  71418. vertices.push(-1, -1);
  71419. vertices.push(1, -1);
  71420. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71421. this._buildIndexBuffer();
  71422. };
  71423. PostProcessManager.prototype._buildIndexBuffer = function () {
  71424. // Indices
  71425. var indices = [];
  71426. indices.push(0);
  71427. indices.push(1);
  71428. indices.push(2);
  71429. indices.push(0);
  71430. indices.push(2);
  71431. indices.push(3);
  71432. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71433. };
  71434. /**
  71435. * Rebuilds the vertex buffers of the manager.
  71436. * @hidden
  71437. */
  71438. PostProcessManager.prototype._rebuild = function () {
  71439. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71440. if (!vb) {
  71441. return;
  71442. }
  71443. vb._rebuild();
  71444. this._buildIndexBuffer();
  71445. };
  71446. // Methods
  71447. /**
  71448. * Prepares a frame to be run through a post process.
  71449. * @param sourceTexture The input texture to the post procesess. (default: null)
  71450. * @param postProcesses An array of post processes to be run. (default: null)
  71451. * @returns True if the post processes were able to be run.
  71452. * @hidden
  71453. */
  71454. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71455. if (sourceTexture === void 0) { sourceTexture = null; }
  71456. if (postProcesses === void 0) { postProcesses = null; }
  71457. var camera = this._scene.activeCamera;
  71458. if (!camera) {
  71459. return false;
  71460. }
  71461. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71462. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71463. return false;
  71464. }
  71465. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71466. return true;
  71467. };
  71468. /**
  71469. * Manually render a set of post processes to a texture.
  71470. * @param postProcesses An array of post processes to be run.
  71471. * @param targetTexture The target texture to render to.
  71472. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71473. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71474. * @param lodLevel defines which lod of the texture to render to
  71475. */
  71476. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71477. if (targetTexture === void 0) { targetTexture = null; }
  71478. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71479. if (faceIndex === void 0) { faceIndex = 0; }
  71480. if (lodLevel === void 0) { lodLevel = 0; }
  71481. var engine = this._scene.getEngine();
  71482. for (var index = 0; index < postProcesses.length; index++) {
  71483. if (index < postProcesses.length - 1) {
  71484. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71485. }
  71486. else {
  71487. if (targetTexture) {
  71488. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71489. }
  71490. else {
  71491. engine.restoreDefaultFramebuffer();
  71492. }
  71493. }
  71494. var pp = postProcesses[index];
  71495. var effect = pp.apply();
  71496. if (effect) {
  71497. pp.onBeforeRenderObservable.notifyObservers(effect);
  71498. // VBOs
  71499. this._prepareBuffers();
  71500. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71501. // Draw order
  71502. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71503. pp.onAfterRenderObservable.notifyObservers(effect);
  71504. }
  71505. }
  71506. // Restore depth buffer
  71507. engine.setDepthBuffer(true);
  71508. engine.setDepthWrite(true);
  71509. };
  71510. /**
  71511. * Finalize the result of the output of the postprocesses.
  71512. * @param doNotPresent If true the result will not be displayed to the screen.
  71513. * @param targetTexture The target texture to render to.
  71514. * @param faceIndex The index of the face to bind the target texture to.
  71515. * @param postProcesses The array of post processes to render.
  71516. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71517. * @hidden
  71518. */
  71519. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71520. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71521. var camera = this._scene.activeCamera;
  71522. if (!camera) {
  71523. return;
  71524. }
  71525. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71526. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71527. return;
  71528. }
  71529. var engine = this._scene.getEngine();
  71530. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71531. var pp = postProcesses[index];
  71532. if (index < len - 1) {
  71533. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71534. }
  71535. else {
  71536. if (targetTexture) {
  71537. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71538. pp._outputTexture = targetTexture;
  71539. }
  71540. else {
  71541. engine.restoreDefaultFramebuffer();
  71542. pp._outputTexture = null;
  71543. }
  71544. }
  71545. if (doNotPresent) {
  71546. break;
  71547. }
  71548. var effect = pp.apply();
  71549. if (effect) {
  71550. pp.onBeforeRenderObservable.notifyObservers(effect);
  71551. // VBOs
  71552. this._prepareBuffers();
  71553. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71554. // Draw order
  71555. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71556. pp.onAfterRenderObservable.notifyObservers(effect);
  71557. }
  71558. }
  71559. // Restore states
  71560. engine.setDepthBuffer(true);
  71561. engine.setDepthWrite(true);
  71562. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71563. };
  71564. /**
  71565. * Disposes of the post process manager.
  71566. */
  71567. PostProcessManager.prototype.dispose = function () {
  71568. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71569. if (buffer) {
  71570. buffer.dispose();
  71571. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71572. }
  71573. if (this._indexBuffer) {
  71574. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71575. this._indexBuffer = null;
  71576. }
  71577. };
  71578. return PostProcessManager;
  71579. }());
  71580. BABYLON.PostProcessManager = PostProcessManager;
  71581. })(BABYLON || (BABYLON = {}));
  71582. //# sourceMappingURL=babylon.postProcessManager.js.map
  71583. var BABYLON;
  71584. (function (BABYLON) {
  71585. /**
  71586. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71587. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71588. */
  71589. var PostProcess = /** @class */ (function () {
  71590. /**
  71591. * Creates a new instance PostProcess
  71592. * @param name The name of the PostProcess.
  71593. * @param fragmentUrl The url of the fragment shader to be used.
  71594. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71595. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71596. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71597. * @param camera The camera to apply the render pass to.
  71598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71599. * @param engine The engine which the post process will be applied. (default: current engine)
  71600. * @param reusable If the post process can be reused on the same frame. (default: false)
  71601. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71602. * @param textureType Type of textures used when performing the post process. (default: 0)
  71603. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71604. * @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
  71605. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71606. */
  71607. function PostProcess(
  71608. /** Name of the PostProcess. */
  71609. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71611. if (defines === void 0) { defines = null; }
  71612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71613. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71614. if (blockCompilation === void 0) { blockCompilation = false; }
  71615. this.name = name;
  71616. /**
  71617. * Width of the texture to apply the post process on
  71618. */
  71619. this.width = -1;
  71620. /**
  71621. * Height of the texture to apply the post process on
  71622. */
  71623. this.height = -1;
  71624. /**
  71625. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71626. * @hidden
  71627. */
  71628. this._outputTexture = null;
  71629. /**
  71630. * If the buffer needs to be cleared before applying the post process. (default: true)
  71631. * Should be set to false if shader will overwrite all previous pixels.
  71632. */
  71633. this.autoClear = true;
  71634. /**
  71635. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71636. */
  71637. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71638. /**
  71639. * Animations to be used for the post processing
  71640. */
  71641. this.animations = new Array();
  71642. /**
  71643. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71644. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71645. */
  71646. this.enablePixelPerfectMode = false;
  71647. /**
  71648. * Force the postprocess to be applied without taking in account viewport
  71649. */
  71650. this.forceFullscreenViewport = true;
  71651. /**
  71652. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71653. *
  71654. * | Value | Type | Description |
  71655. * | ----- | ----------------------------------- | ----------- |
  71656. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71657. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71658. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71659. *
  71660. */
  71661. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71662. /**
  71663. * Force textures to be a power of two (default: false)
  71664. */
  71665. this.alwaysForcePOT = false;
  71666. this._samples = 1;
  71667. /**
  71668. * Modify the scale of the post process to be the same as the viewport (default: false)
  71669. */
  71670. this.adaptScaleToCurrentViewport = false;
  71671. this._reusable = false;
  71672. /**
  71673. * Smart array of input and output textures for the post process.
  71674. * @hidden
  71675. */
  71676. this._textures = new BABYLON.SmartArray(2);
  71677. /**
  71678. * The index in _textures that corresponds to the output texture.
  71679. * @hidden
  71680. */
  71681. this._currentRenderTextureInd = 0;
  71682. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71683. this._texelSize = BABYLON.Vector2.Zero();
  71684. // Events
  71685. /**
  71686. * An event triggered when the postprocess is activated.
  71687. */
  71688. this.onActivateObservable = new BABYLON.Observable();
  71689. /**
  71690. * An event triggered when the postprocess changes its size.
  71691. */
  71692. this.onSizeChangedObservable = new BABYLON.Observable();
  71693. /**
  71694. * An event triggered when the postprocess applies its effect.
  71695. */
  71696. this.onApplyObservable = new BABYLON.Observable();
  71697. /**
  71698. * An event triggered before rendering the postprocess
  71699. */
  71700. this.onBeforeRenderObservable = new BABYLON.Observable();
  71701. /**
  71702. * An event triggered after rendering the postprocess
  71703. */
  71704. this.onAfterRenderObservable = new BABYLON.Observable();
  71705. if (camera != null) {
  71706. this._camera = camera;
  71707. this._scene = camera.getScene();
  71708. camera.attachPostProcess(this);
  71709. this._engine = this._scene.getEngine();
  71710. this._scene.postProcesses.push(this);
  71711. }
  71712. else if (engine) {
  71713. this._engine = engine;
  71714. this._engine.postProcesses.push(this);
  71715. }
  71716. this._options = options;
  71717. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71718. this._reusable = reusable || false;
  71719. this._textureType = textureType;
  71720. this._samplers = samplers || [];
  71721. this._samplers.push("textureSampler");
  71722. this._fragmentUrl = fragmentUrl;
  71723. this._vertexUrl = vertexUrl;
  71724. this._parameters = parameters || [];
  71725. this._parameters.push("scale");
  71726. this._indexParameters = indexParameters;
  71727. if (!blockCompilation) {
  71728. this.updateEffect(defines);
  71729. }
  71730. }
  71731. Object.defineProperty(PostProcess.prototype, "samples", {
  71732. /**
  71733. * Number of sample textures (default: 1)
  71734. */
  71735. get: function () {
  71736. return this._samples;
  71737. },
  71738. set: function (n) {
  71739. var _this = this;
  71740. this._samples = n;
  71741. this._textures.forEach(function (texture) {
  71742. if (texture.samples !== _this._samples) {
  71743. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71744. }
  71745. });
  71746. },
  71747. enumerable: true,
  71748. configurable: true
  71749. });
  71750. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71751. /**
  71752. * A function that is added to the onActivateObservable
  71753. */
  71754. set: function (callback) {
  71755. if (this._onActivateObserver) {
  71756. this.onActivateObservable.remove(this._onActivateObserver);
  71757. }
  71758. if (callback) {
  71759. this._onActivateObserver = this.onActivateObservable.add(callback);
  71760. }
  71761. },
  71762. enumerable: true,
  71763. configurable: true
  71764. });
  71765. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71766. /**
  71767. * A function that is added to the onSizeChangedObservable
  71768. */
  71769. set: function (callback) {
  71770. if (this._onSizeChangedObserver) {
  71771. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71772. }
  71773. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71774. },
  71775. enumerable: true,
  71776. configurable: true
  71777. });
  71778. Object.defineProperty(PostProcess.prototype, "onApply", {
  71779. /**
  71780. * A function that is added to the onApplyObservable
  71781. */
  71782. set: function (callback) {
  71783. if (this._onApplyObserver) {
  71784. this.onApplyObservable.remove(this._onApplyObserver);
  71785. }
  71786. this._onApplyObserver = this.onApplyObservable.add(callback);
  71787. },
  71788. enumerable: true,
  71789. configurable: true
  71790. });
  71791. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71792. /**
  71793. * A function that is added to the onBeforeRenderObservable
  71794. */
  71795. set: function (callback) {
  71796. if (this._onBeforeRenderObserver) {
  71797. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71798. }
  71799. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71800. },
  71801. enumerable: true,
  71802. configurable: true
  71803. });
  71804. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71805. /**
  71806. * A function that is added to the onAfterRenderObservable
  71807. */
  71808. set: function (callback) {
  71809. if (this._onAfterRenderObserver) {
  71810. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71811. }
  71812. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71813. },
  71814. enumerable: true,
  71815. configurable: true
  71816. });
  71817. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71818. /**
  71819. * 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
  71820. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71821. */
  71822. get: function () {
  71823. return this._textures.data[this._currentRenderTextureInd];
  71824. },
  71825. set: function (value) {
  71826. this._forcedOutputTexture = value;
  71827. },
  71828. enumerable: true,
  71829. configurable: true
  71830. });
  71831. /**
  71832. * Gets the camera which post process is applied to.
  71833. * @returns The camera the post process is applied to.
  71834. */
  71835. PostProcess.prototype.getCamera = function () {
  71836. return this._camera;
  71837. };
  71838. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71839. /**
  71840. * Gets the texel size of the postprocess.
  71841. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71842. */
  71843. get: function () {
  71844. if (this._shareOutputWithPostProcess) {
  71845. return this._shareOutputWithPostProcess.texelSize;
  71846. }
  71847. if (this._forcedOutputTexture) {
  71848. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71849. }
  71850. return this._texelSize;
  71851. },
  71852. enumerable: true,
  71853. configurable: true
  71854. });
  71855. /**
  71856. * Gets the engine which this post process belongs to.
  71857. * @returns The engine the post process was enabled with.
  71858. */
  71859. PostProcess.prototype.getEngine = function () {
  71860. return this._engine;
  71861. };
  71862. /**
  71863. * The effect that is created when initializing the post process.
  71864. * @returns The created effect corrisponding the the postprocess.
  71865. */
  71866. PostProcess.prototype.getEffect = function () {
  71867. return this._effect;
  71868. };
  71869. /**
  71870. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71871. * @param postProcess The post process to share the output with.
  71872. * @returns This post process.
  71873. */
  71874. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71875. this._disposeTextures();
  71876. this._shareOutputWithPostProcess = postProcess;
  71877. return this;
  71878. };
  71879. /**
  71880. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71881. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71882. */
  71883. PostProcess.prototype.useOwnOutput = function () {
  71884. if (this._textures.length == 0) {
  71885. this._textures = new BABYLON.SmartArray(2);
  71886. }
  71887. this._shareOutputWithPostProcess = null;
  71888. };
  71889. /**
  71890. * Updates the effect with the current post process compile time values and recompiles the shader.
  71891. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71892. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71893. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71894. * @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
  71895. * @param onCompiled Called when the shader has been compiled.
  71896. * @param onError Called if there is an error when compiling a shader.
  71897. */
  71898. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71899. if (defines === void 0) { defines = null; }
  71900. if (uniforms === void 0) { uniforms = null; }
  71901. if (samplers === void 0) { samplers = null; }
  71902. 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);
  71903. };
  71904. /**
  71905. * The post process is reusable if it can be used multiple times within one frame.
  71906. * @returns If the post process is reusable
  71907. */
  71908. PostProcess.prototype.isReusable = function () {
  71909. return this._reusable;
  71910. };
  71911. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71912. PostProcess.prototype.markTextureDirty = function () {
  71913. this.width = -1;
  71914. };
  71915. /**
  71916. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71917. * 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.
  71918. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71919. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71920. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71921. * @returns The target texture that was bound to be written to.
  71922. */
  71923. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71924. var _this = this;
  71925. if (sourceTexture === void 0) { sourceTexture = null; }
  71926. camera = camera || this._camera;
  71927. var scene = camera.getScene();
  71928. var engine = scene.getEngine();
  71929. var maxSize = engine.getCaps().maxTextureSize;
  71930. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71931. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71932. // 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
  71933. var webVRCamera = camera.parent;
  71934. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71935. requiredWidth /= 2;
  71936. }
  71937. var desiredWidth = (this._options.width || requiredWidth);
  71938. var desiredHeight = this._options.height || requiredHeight;
  71939. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71940. if (this.adaptScaleToCurrentViewport) {
  71941. var currentViewport = engine.currentViewport;
  71942. if (currentViewport) {
  71943. desiredWidth *= currentViewport.width;
  71944. desiredHeight *= currentViewport.height;
  71945. }
  71946. }
  71947. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71948. if (!this._options.width) {
  71949. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71950. }
  71951. if (!this._options.height) {
  71952. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71953. }
  71954. }
  71955. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71956. if (this._textures.length > 0) {
  71957. for (var i = 0; i < this._textures.length; i++) {
  71958. this._engine._releaseTexture(this._textures.data[i]);
  71959. }
  71960. this._textures.reset();
  71961. }
  71962. this.width = desiredWidth;
  71963. this.height = desiredHeight;
  71964. var textureSize = { width: this.width, height: this.height };
  71965. var textureOptions = {
  71966. generateMipMaps: false,
  71967. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71968. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71969. samplingMode: this.renderTargetSamplingMode,
  71970. type: this._textureType
  71971. };
  71972. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71973. if (this._reusable) {
  71974. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71975. }
  71976. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  71977. this.onSizeChangedObservable.notifyObservers(this);
  71978. }
  71979. this._textures.forEach(function (texture) {
  71980. if (texture.samples !== _this.samples) {
  71981. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  71982. }
  71983. });
  71984. }
  71985. var target;
  71986. if (this._shareOutputWithPostProcess) {
  71987. target = this._shareOutputWithPostProcess.inputTexture;
  71988. }
  71989. else if (this._forcedOutputTexture) {
  71990. target = this._forcedOutputTexture;
  71991. this.width = this._forcedOutputTexture.width;
  71992. this.height = this._forcedOutputTexture.height;
  71993. }
  71994. else {
  71995. target = this.inputTexture;
  71996. }
  71997. // Bind the input of this post process to be used as the output of the previous post process.
  71998. if (this.enablePixelPerfectMode) {
  71999. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72000. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72001. }
  72002. else {
  72003. this._scaleRatio.copyFromFloats(1, 1);
  72004. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72005. }
  72006. this.onActivateObservable.notifyObservers(camera);
  72007. // Clear
  72008. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72009. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72010. }
  72011. if (this._reusable) {
  72012. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72013. }
  72014. return target;
  72015. };
  72016. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72017. /**
  72018. * If the post process is supported.
  72019. */
  72020. get: function () {
  72021. return this._effect.isSupported;
  72022. },
  72023. enumerable: true,
  72024. configurable: true
  72025. });
  72026. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72027. /**
  72028. * The aspect ratio of the output texture.
  72029. */
  72030. get: function () {
  72031. if (this._shareOutputWithPostProcess) {
  72032. return this._shareOutputWithPostProcess.aspectRatio;
  72033. }
  72034. if (this._forcedOutputTexture) {
  72035. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  72036. }
  72037. return this.width / this.height;
  72038. },
  72039. enumerable: true,
  72040. configurable: true
  72041. });
  72042. /**
  72043. * Get a value indicating if the post-process is ready to be used
  72044. * @returns true if the post-process is ready (shader is compiled)
  72045. */
  72046. PostProcess.prototype.isReady = function () {
  72047. return this._effect && this._effect.isReady();
  72048. };
  72049. /**
  72050. * Binds all textures and uniforms to the shader, this will be run on every pass.
  72051. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  72052. */
  72053. PostProcess.prototype.apply = function () {
  72054. // Check
  72055. if (!this._effect || !this._effect.isReady())
  72056. return null;
  72057. // States
  72058. this._engine.enableEffect(this._effect);
  72059. this._engine.setState(false);
  72060. this._engine.setDepthBuffer(false);
  72061. this._engine.setDepthWrite(false);
  72062. // Alpha
  72063. this._engine.setAlphaMode(this.alphaMode);
  72064. if (this.alphaConstants) {
  72065. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  72066. }
  72067. // Bind the output texture of the preivous post process as the input to this post process.
  72068. var source;
  72069. if (this._shareOutputWithPostProcess) {
  72070. source = this._shareOutputWithPostProcess.inputTexture;
  72071. }
  72072. else if (this._forcedOutputTexture) {
  72073. source = this._forcedOutputTexture;
  72074. }
  72075. else {
  72076. source = this.inputTexture;
  72077. }
  72078. this._effect._bindTexture("textureSampler", source);
  72079. // Parameters
  72080. this._effect.setVector2("scale", this._scaleRatio);
  72081. this.onApplyObservable.notifyObservers(this._effect);
  72082. return this._effect;
  72083. };
  72084. PostProcess.prototype._disposeTextures = function () {
  72085. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  72086. return;
  72087. }
  72088. if (this._textures.length > 0) {
  72089. for (var i = 0; i < this._textures.length; i++) {
  72090. this._engine._releaseTexture(this._textures.data[i]);
  72091. }
  72092. }
  72093. this._textures.dispose();
  72094. };
  72095. /**
  72096. * Disposes the post process.
  72097. * @param camera The camera to dispose the post process on.
  72098. */
  72099. PostProcess.prototype.dispose = function (camera) {
  72100. camera = camera || this._camera;
  72101. this._disposeTextures();
  72102. if (this._scene) {
  72103. var index_1 = this._scene.postProcesses.indexOf(this);
  72104. if (index_1 !== -1) {
  72105. this._scene.postProcesses.splice(index_1, 1);
  72106. }
  72107. }
  72108. else {
  72109. var index_2 = this._engine.postProcesses.indexOf(this);
  72110. if (index_2 !== -1) {
  72111. this._engine.postProcesses.splice(index_2, 1);
  72112. }
  72113. }
  72114. if (!camera) {
  72115. return;
  72116. }
  72117. camera.detachPostProcess(this);
  72118. var index = camera._postProcesses.indexOf(this);
  72119. if (index === 0 && camera._postProcesses.length > 0) {
  72120. var firstPostProcess = this._camera._getFirstPostProcess();
  72121. if (firstPostProcess) {
  72122. firstPostProcess.markTextureDirty();
  72123. }
  72124. }
  72125. this.onActivateObservable.clear();
  72126. this.onAfterRenderObservable.clear();
  72127. this.onApplyObservable.clear();
  72128. this.onBeforeRenderObservable.clear();
  72129. this.onSizeChangedObservable.clear();
  72130. };
  72131. return PostProcess;
  72132. }());
  72133. BABYLON.PostProcess = PostProcess;
  72134. })(BABYLON || (BABYLON = {}));
  72135. //# sourceMappingURL=babylon.postProcess.js.map
  72136. var BABYLON;
  72137. (function (BABYLON) {
  72138. var PassPostProcess = /** @class */ (function (_super) {
  72139. __extends(PassPostProcess, _super);
  72140. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72141. if (camera === void 0) { camera = null; }
  72142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72143. if (blockCompilation === void 0) { blockCompilation = false; }
  72144. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  72145. }
  72146. return PassPostProcess;
  72147. }(BABYLON.PostProcess));
  72148. BABYLON.PassPostProcess = PassPostProcess;
  72149. })(BABYLON || (BABYLON = {}));
  72150. //# sourceMappingURL=babylon.passPostProcess.js.map
  72151. var __assign = (this && this.__assign) || function () {
  72152. __assign = Object.assign || function(t) {
  72153. for (var s, i = 1, n = arguments.length; i < n; i++) {
  72154. s = arguments[i];
  72155. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  72156. t[p] = s[p];
  72157. }
  72158. return t;
  72159. };
  72160. return __assign.apply(this, arguments);
  72161. };
  72162. var BABYLON;
  72163. (function (BABYLON) {
  72164. /**
  72165. * Default implementation IShadowGenerator.
  72166. * This is the main object responsible of generating shadows in the framework.
  72167. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  72168. */
  72169. var ShadowGenerator = /** @class */ (function () {
  72170. /**
  72171. * Creates a ShadowGenerator object.
  72172. * A ShadowGenerator is the required tool to use the shadows.
  72173. * Each light casting shadows needs to use its own ShadowGenerator.
  72174. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  72175. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  72176. * @param light The light object generating the shadows.
  72177. * @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.
  72178. */
  72179. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  72180. this._bias = 0.00005;
  72181. this._normalBias = 0;
  72182. this._blurBoxOffset = 1;
  72183. this._blurScale = 2;
  72184. this._blurKernel = 1;
  72185. this._useKernelBlur = false;
  72186. this._filter = ShadowGenerator.FILTER_NONE;
  72187. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  72188. this._contactHardeningLightSizeUVRatio = 0.1;
  72189. this._darkness = 0;
  72190. this._transparencyShadow = false;
  72191. /**
  72192. * Controls the extent to which the shadows fade out at the edge of the frustum
  72193. * Used only by directionals and spots
  72194. */
  72195. this.frustumEdgeFalloff = 0;
  72196. /**
  72197. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  72198. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  72199. * It might on the other hand introduce peter panning.
  72200. */
  72201. this.forceBackFacesOnly = false;
  72202. this._lightDirection = BABYLON.Vector3.Zero();
  72203. this._viewMatrix = BABYLON.Matrix.Zero();
  72204. this._projectionMatrix = BABYLON.Matrix.Zero();
  72205. this._transformMatrix = BABYLON.Matrix.Zero();
  72206. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72207. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72208. this._currentFaceIndex = 0;
  72209. this._currentFaceIndexCache = 0;
  72210. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  72211. this._mapSize = mapSize;
  72212. this._light = light;
  72213. this._scene = light.getScene();
  72214. light._shadowGenerator = this;
  72215. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  72216. if (!component) {
  72217. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  72218. this._scene._addComponent(component);
  72219. }
  72220. // Texture type fallback from float to int if not supported.
  72221. var caps = this._scene.getEngine().getCaps();
  72222. if (!useFullFloatFirst) {
  72223. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72224. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72225. }
  72226. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72227. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72228. }
  72229. else {
  72230. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72231. }
  72232. }
  72233. else {
  72234. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72235. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72236. }
  72237. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72238. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72239. }
  72240. else {
  72241. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72242. }
  72243. }
  72244. this._initializeGenerator();
  72245. this._applyFilterValues();
  72246. }
  72247. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  72248. /**
  72249. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  72250. */
  72251. get: function () {
  72252. return this._bias;
  72253. },
  72254. /**
  72255. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  72256. */
  72257. set: function (bias) {
  72258. this._bias = bias;
  72259. },
  72260. enumerable: true,
  72261. configurable: true
  72262. });
  72263. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  72264. /**
  72265. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72266. */
  72267. get: function () {
  72268. return this._normalBias;
  72269. },
  72270. /**
  72271. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72272. */
  72273. set: function (normalBias) {
  72274. this._normalBias = normalBias;
  72275. },
  72276. enumerable: true,
  72277. configurable: true
  72278. });
  72279. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  72280. /**
  72281. * Gets the blur box offset: offset applied during the blur pass.
  72282. * Only usefull if useKernelBlur = false
  72283. */
  72284. get: function () {
  72285. return this._blurBoxOffset;
  72286. },
  72287. /**
  72288. * Sets the blur box offset: offset applied during the blur pass.
  72289. * Only usefull if useKernelBlur = false
  72290. */
  72291. set: function (value) {
  72292. if (this._blurBoxOffset === value) {
  72293. return;
  72294. }
  72295. this._blurBoxOffset = value;
  72296. this._disposeBlurPostProcesses();
  72297. },
  72298. enumerable: true,
  72299. configurable: true
  72300. });
  72301. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72302. /**
  72303. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72304. * 2 means half of the size.
  72305. */
  72306. get: function () {
  72307. return this._blurScale;
  72308. },
  72309. /**
  72310. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72311. * 2 means half of the size.
  72312. */
  72313. set: function (value) {
  72314. if (this._blurScale === value) {
  72315. return;
  72316. }
  72317. this._blurScale = value;
  72318. this._disposeBlurPostProcesses();
  72319. },
  72320. enumerable: true,
  72321. configurable: true
  72322. });
  72323. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72324. /**
  72325. * Gets the blur kernel: kernel size of the blur pass.
  72326. * Only usefull if useKernelBlur = true
  72327. */
  72328. get: function () {
  72329. return this._blurKernel;
  72330. },
  72331. /**
  72332. * Sets the blur kernel: kernel size of the blur pass.
  72333. * Only usefull if useKernelBlur = true
  72334. */
  72335. set: function (value) {
  72336. if (this._blurKernel === value) {
  72337. return;
  72338. }
  72339. this._blurKernel = value;
  72340. this._disposeBlurPostProcesses();
  72341. },
  72342. enumerable: true,
  72343. configurable: true
  72344. });
  72345. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72346. /**
  72347. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72348. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72349. */
  72350. get: function () {
  72351. return this._useKernelBlur;
  72352. },
  72353. /**
  72354. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72355. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72356. */
  72357. set: function (value) {
  72358. if (this._useKernelBlur === value) {
  72359. return;
  72360. }
  72361. this._useKernelBlur = value;
  72362. this._disposeBlurPostProcesses();
  72363. },
  72364. enumerable: true,
  72365. configurable: true
  72366. });
  72367. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72368. /**
  72369. * Gets the depth scale used in ESM mode.
  72370. */
  72371. get: function () {
  72372. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72373. },
  72374. /**
  72375. * Sets the depth scale used in ESM mode.
  72376. * This can override the scale stored on the light.
  72377. */
  72378. set: function (value) {
  72379. this._depthScale = value;
  72380. },
  72381. enumerable: true,
  72382. configurable: true
  72383. });
  72384. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72385. /**
  72386. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72387. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72388. */
  72389. get: function () {
  72390. return this._filter;
  72391. },
  72392. /**
  72393. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72394. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72395. */
  72396. set: function (value) {
  72397. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72398. if (this._light.needCube()) {
  72399. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72400. this.useExponentialShadowMap = true;
  72401. return;
  72402. }
  72403. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72404. this.useCloseExponentialShadowMap = true;
  72405. return;
  72406. }
  72407. // PCF on cubemap would also be expensive
  72408. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72409. this.usePoissonSampling = true;
  72410. return;
  72411. }
  72412. }
  72413. // Weblg1 fallback for PCF.
  72414. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72415. if (this._scene.getEngine().webGLVersion === 1) {
  72416. this.usePoissonSampling = true;
  72417. return;
  72418. }
  72419. }
  72420. if (this._filter === value) {
  72421. return;
  72422. }
  72423. this._filter = value;
  72424. this._disposeBlurPostProcesses();
  72425. this._applyFilterValues();
  72426. this._light._markMeshesAsLightDirty();
  72427. },
  72428. enumerable: true,
  72429. configurable: true
  72430. });
  72431. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72432. /**
  72433. * Gets if the current filter is set to Poisson Sampling.
  72434. */
  72435. get: function () {
  72436. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72437. },
  72438. /**
  72439. * Sets the current filter to Poisson Sampling.
  72440. */
  72441. set: function (value) {
  72442. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72443. return;
  72444. }
  72445. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72446. },
  72447. enumerable: true,
  72448. configurable: true
  72449. });
  72450. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72451. /**
  72452. * Gets if the current filter is set to VSM.
  72453. * DEPRECATED. Should use useExponentialShadowMap instead.
  72454. */
  72455. get: function () {
  72456. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72457. return this.useExponentialShadowMap;
  72458. },
  72459. /**
  72460. * Sets the current filter is to VSM.
  72461. * DEPRECATED. Should use useExponentialShadowMap instead.
  72462. */
  72463. set: function (value) {
  72464. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72465. this.useExponentialShadowMap = value;
  72466. },
  72467. enumerable: true,
  72468. configurable: true
  72469. });
  72470. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72471. /**
  72472. * Gets if the current filter is set to blurred VSM.
  72473. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72474. */
  72475. get: function () {
  72476. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72477. return this.useBlurExponentialShadowMap;
  72478. },
  72479. /**
  72480. * Sets the current filter is to blurred VSM.
  72481. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72482. */
  72483. set: function (value) {
  72484. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72485. this.useBlurExponentialShadowMap = value;
  72486. },
  72487. enumerable: true,
  72488. configurable: true
  72489. });
  72490. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72491. /**
  72492. * Gets if the current filter is set to ESM.
  72493. */
  72494. get: function () {
  72495. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72496. },
  72497. /**
  72498. * Sets the current filter is to ESM.
  72499. */
  72500. set: function (value) {
  72501. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72502. return;
  72503. }
  72504. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72505. },
  72506. enumerable: true,
  72507. configurable: true
  72508. });
  72509. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72510. /**
  72511. * Gets if the current filter is set to filtered ESM.
  72512. */
  72513. get: function () {
  72514. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72515. },
  72516. /**
  72517. * Gets if the current filter is set to filtered ESM.
  72518. */
  72519. set: function (value) {
  72520. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72521. return;
  72522. }
  72523. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72524. },
  72525. enumerable: true,
  72526. configurable: true
  72527. });
  72528. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72529. /**
  72530. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72531. * exponential to prevent steep falloff artifacts).
  72532. */
  72533. get: function () {
  72534. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72535. },
  72536. /**
  72537. * Sets the current filter to "close ESM" (using the inverse of the
  72538. * exponential to prevent steep falloff artifacts).
  72539. */
  72540. set: function (value) {
  72541. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72542. return;
  72543. }
  72544. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72545. },
  72546. enumerable: true,
  72547. configurable: true
  72548. });
  72549. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72550. /**
  72551. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72552. * exponential to prevent steep falloff artifacts).
  72553. */
  72554. get: function () {
  72555. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72556. },
  72557. /**
  72558. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72559. * exponential to prevent steep falloff artifacts).
  72560. */
  72561. set: function (value) {
  72562. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72563. return;
  72564. }
  72565. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72566. },
  72567. enumerable: true,
  72568. configurable: true
  72569. });
  72570. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72571. /**
  72572. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72573. */
  72574. get: function () {
  72575. return this.filter === ShadowGenerator.FILTER_PCF;
  72576. },
  72577. /**
  72578. * Sets the current filter to "PCF" (percentage closer filtering).
  72579. */
  72580. set: function (value) {
  72581. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72582. return;
  72583. }
  72584. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72585. },
  72586. enumerable: true,
  72587. configurable: true
  72588. });
  72589. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72590. /**
  72591. * Gets the PCF or PCSS Quality.
  72592. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72593. */
  72594. get: function () {
  72595. return this._filteringQuality;
  72596. },
  72597. /**
  72598. * Sets the PCF or PCSS Quality.
  72599. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72600. */
  72601. set: function (filteringQuality) {
  72602. this._filteringQuality = filteringQuality;
  72603. },
  72604. enumerable: true,
  72605. configurable: true
  72606. });
  72607. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72608. /**
  72609. * Gets if the current filter is set to "PCSS" (contact hardening).
  72610. */
  72611. get: function () {
  72612. return this.filter === ShadowGenerator.FILTER_PCSS;
  72613. },
  72614. /**
  72615. * Sets the current filter to "PCSS" (contact hardening).
  72616. */
  72617. set: function (value) {
  72618. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72619. return;
  72620. }
  72621. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72622. },
  72623. enumerable: true,
  72624. configurable: true
  72625. });
  72626. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72627. /**
  72628. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72629. * Using a ratio helps keeping shape stability independently of the map size.
  72630. *
  72631. * It does not account for the light projection as it was having too much
  72632. * instability during the light setup or during light position changes.
  72633. *
  72634. * Only valid if useContactHardeningShadow is true.
  72635. */
  72636. get: function () {
  72637. return this._contactHardeningLightSizeUVRatio;
  72638. },
  72639. /**
  72640. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72641. * Using a ratio helps keeping shape stability independently of the map size.
  72642. *
  72643. * It does not account for the light projection as it was having too much
  72644. * instability during the light setup or during light position changes.
  72645. *
  72646. * Only valid if useContactHardeningShadow is true.
  72647. */
  72648. set: function (contactHardeningLightSizeUVRatio) {
  72649. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72650. },
  72651. enumerable: true,
  72652. configurable: true
  72653. });
  72654. /**
  72655. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72656. * 0 means strongest and 1 would means no shadow.
  72657. * @returns the darkness.
  72658. */
  72659. ShadowGenerator.prototype.getDarkness = function () {
  72660. return this._darkness;
  72661. };
  72662. /**
  72663. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72664. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72665. * @returns the shadow generator allowing fluent coding.
  72666. */
  72667. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72668. if (darkness >= 1.0)
  72669. this._darkness = 1.0;
  72670. else if (darkness <= 0.0)
  72671. this._darkness = 0.0;
  72672. else
  72673. this._darkness = darkness;
  72674. return this;
  72675. };
  72676. /**
  72677. * Sets the ability to have transparent shadow (boolean).
  72678. * @param transparent True if transparent else False
  72679. * @returns the shadow generator allowing fluent coding
  72680. */
  72681. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72682. this._transparencyShadow = transparent;
  72683. return this;
  72684. };
  72685. /**
  72686. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72687. * @returns The render target texture if present otherwise, null
  72688. */
  72689. ShadowGenerator.prototype.getShadowMap = function () {
  72690. return this._shadowMap;
  72691. };
  72692. /**
  72693. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72694. * @returns The render target texture if the shadow map is present otherwise, null
  72695. */
  72696. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72697. if (this._shadowMap2) {
  72698. return this._shadowMap2;
  72699. }
  72700. return this._shadowMap;
  72701. };
  72702. /**
  72703. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72704. * @param mesh Mesh to add
  72705. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72706. * @returns the Shadow Generator itself
  72707. */
  72708. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72709. if (includeDescendants === void 0) { includeDescendants = true; }
  72710. var _a;
  72711. if (!this._shadowMap) {
  72712. return this;
  72713. }
  72714. if (!this._shadowMap.renderList) {
  72715. this._shadowMap.renderList = [];
  72716. }
  72717. this._shadowMap.renderList.push(mesh);
  72718. if (includeDescendants) {
  72719. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72720. }
  72721. return this;
  72722. };
  72723. /**
  72724. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72725. * @param mesh Mesh to remove
  72726. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72727. * @returns the Shadow Generator itself
  72728. */
  72729. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72730. if (includeDescendants === void 0) { includeDescendants = true; }
  72731. if (!this._shadowMap || !this._shadowMap.renderList) {
  72732. return this;
  72733. }
  72734. var index = this._shadowMap.renderList.indexOf(mesh);
  72735. if (index !== -1) {
  72736. this._shadowMap.renderList.splice(index, 1);
  72737. }
  72738. if (includeDescendants) {
  72739. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72740. var child = _a[_i];
  72741. this.removeShadowCaster(child);
  72742. }
  72743. }
  72744. return this;
  72745. };
  72746. /**
  72747. * Returns the associated light object.
  72748. * @returns the light generating the shadow
  72749. */
  72750. ShadowGenerator.prototype.getLight = function () {
  72751. return this._light;
  72752. };
  72753. ShadowGenerator.prototype._initializeGenerator = function () {
  72754. this._light._markMeshesAsLightDirty();
  72755. this._initializeShadowMap();
  72756. };
  72757. ShadowGenerator.prototype._initializeShadowMap = function () {
  72758. var _this = this;
  72759. // Render target
  72760. var engine = this._scene.getEngine();
  72761. if (engine.webGLVersion > 1) {
  72762. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72763. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72764. }
  72765. else {
  72766. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72767. }
  72768. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72769. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72770. this._shadowMap.anisotropicFilteringLevel = 1;
  72771. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72772. this._shadowMap.renderParticles = false;
  72773. this._shadowMap.ignoreCameraViewport = true;
  72774. // Record Face Index before render.
  72775. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72776. _this._currentFaceIndex = faceIndex;
  72777. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72778. engine.setColorWrite(false);
  72779. }
  72780. });
  72781. // Custom render function.
  72782. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72783. // Blur if required afer render.
  72784. this._shadowMap.onAfterUnbindObservable.add(function () {
  72785. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72786. engine.setColorWrite(true);
  72787. }
  72788. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72789. return;
  72790. }
  72791. var shadowMap = _this.getShadowMapForRendering();
  72792. if (shadowMap) {
  72793. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72794. }
  72795. });
  72796. // Clear according to the chosen filter.
  72797. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72798. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72799. this._shadowMap.onClearObservable.add(function (engine) {
  72800. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72801. engine.clear(clearOne, false, true, false);
  72802. }
  72803. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72804. engine.clear(clearZero, true, true, false);
  72805. }
  72806. else {
  72807. engine.clear(clearOne, true, true, false);
  72808. }
  72809. });
  72810. };
  72811. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72812. var _this = this;
  72813. var engine = this._scene.getEngine();
  72814. var targetSize = this._mapSize / this.blurScale;
  72815. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72816. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72817. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72818. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72819. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72820. }
  72821. if (this.useKernelBlur) {
  72822. 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);
  72823. this._kernelBlurXPostprocess.width = targetSize;
  72824. this._kernelBlurXPostprocess.height = targetSize;
  72825. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72826. effect.setTexture("textureSampler", _this._shadowMap);
  72827. });
  72828. 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);
  72829. this._kernelBlurXPostprocess.autoClear = false;
  72830. this._kernelBlurYPostprocess.autoClear = false;
  72831. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72832. this._kernelBlurXPostprocess.packedFloat = true;
  72833. this._kernelBlurYPostprocess.packedFloat = true;
  72834. }
  72835. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72836. }
  72837. else {
  72838. 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);
  72839. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72840. effect.setFloat2("screenSize", targetSize, targetSize);
  72841. effect.setTexture("textureSampler", _this._shadowMap);
  72842. });
  72843. this._boxBlurPostprocess.autoClear = false;
  72844. this._blurPostProcesses = [this._boxBlurPostprocess];
  72845. }
  72846. };
  72847. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72848. var index;
  72849. var engine = this._scene.getEngine();
  72850. if (depthOnlySubMeshes.length) {
  72851. engine.setColorWrite(false);
  72852. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72853. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72854. }
  72855. engine.setColorWrite(true);
  72856. }
  72857. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72858. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72859. }
  72860. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72861. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72862. }
  72863. if (this._transparencyShadow) {
  72864. for (index = 0; index < transparentSubMeshes.length; index++) {
  72865. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72866. }
  72867. }
  72868. };
  72869. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72870. var _this = this;
  72871. var mesh = subMesh.getRenderingMesh();
  72872. var scene = this._scene;
  72873. var engine = scene.getEngine();
  72874. var material = subMesh.getMaterial();
  72875. if (!material) {
  72876. return;
  72877. }
  72878. // Culling
  72879. engine.setState(material.backFaceCulling);
  72880. // Managing instances
  72881. var batch = mesh._getInstancesRenderList(subMesh._id);
  72882. if (batch.mustReturn) {
  72883. return;
  72884. }
  72885. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72886. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72887. engine.enableEffect(this._effect);
  72888. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72889. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72890. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72891. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72892. this._effect.setVector3("lightData", this._cachedDirection);
  72893. }
  72894. else {
  72895. this._effect.setVector3("lightData", this._cachedPosition);
  72896. }
  72897. if (scene.activeCamera) {
  72898. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72899. }
  72900. // Alpha test
  72901. if (material && material.needAlphaTesting()) {
  72902. var alphaTexture = material.getAlphaTestTexture();
  72903. if (alphaTexture) {
  72904. this._effect.setTexture("diffuseSampler", alphaTexture);
  72905. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72906. }
  72907. }
  72908. // Bones
  72909. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72910. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72911. }
  72912. // Morph targets
  72913. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72914. if (this.forceBackFacesOnly) {
  72915. engine.setState(true, 0, false, true);
  72916. }
  72917. // Draw
  72918. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72919. if (this.forceBackFacesOnly) {
  72920. engine.setState(true, 0, false, false);
  72921. }
  72922. }
  72923. else {
  72924. // Need to reset refresh rate of the shadowMap
  72925. if (this._shadowMap) {
  72926. this._shadowMap.resetRefreshCounter();
  72927. }
  72928. }
  72929. };
  72930. ShadowGenerator.prototype._applyFilterValues = function () {
  72931. if (!this._shadowMap) {
  72932. return;
  72933. }
  72934. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72935. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72936. }
  72937. else {
  72938. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72939. }
  72940. };
  72941. /**
  72942. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72943. * @param onCompiled Callback triggered at the and of the effects compilation
  72944. * @param options Sets of optional options forcing the compilation with different modes
  72945. */
  72946. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72947. var _this = this;
  72948. var localOptions = __assign({ useInstances: false }, options);
  72949. var shadowMap = this.getShadowMap();
  72950. if (!shadowMap) {
  72951. if (onCompiled) {
  72952. onCompiled(this);
  72953. }
  72954. return;
  72955. }
  72956. var renderList = shadowMap.renderList;
  72957. if (!renderList) {
  72958. if (onCompiled) {
  72959. onCompiled(this);
  72960. }
  72961. return;
  72962. }
  72963. var subMeshes = new Array();
  72964. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72965. var mesh = renderList_1[_i];
  72966. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72967. }
  72968. if (subMeshes.length === 0) {
  72969. if (onCompiled) {
  72970. onCompiled(this);
  72971. }
  72972. return;
  72973. }
  72974. var currentIndex = 0;
  72975. var checkReady = function () {
  72976. if (!_this._scene || !_this._scene.getEngine()) {
  72977. return;
  72978. }
  72979. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  72980. currentIndex++;
  72981. if (currentIndex >= subMeshes.length) {
  72982. if (onCompiled) {
  72983. onCompiled(_this);
  72984. }
  72985. return;
  72986. }
  72987. }
  72988. setTimeout(checkReady, 16);
  72989. };
  72990. checkReady();
  72991. };
  72992. /**
  72993. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72994. * @param options Sets of optional options forcing the compilation with different modes
  72995. * @returns A promise that resolves when the compilation completes
  72996. */
  72997. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  72998. var _this = this;
  72999. return new Promise(function (resolve) {
  73000. _this.forceCompilation(function () {
  73001. resolve();
  73002. }, options);
  73003. });
  73004. };
  73005. /**
  73006. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73007. * @param subMesh The submesh we want to render in the shadow map
  73008. * @param useInstances Defines wether will draw in the map using instances
  73009. * @returns true if ready otherwise, false
  73010. */
  73011. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73012. var defines = [];
  73013. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73014. defines.push("#define FLOAT");
  73015. }
  73016. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73017. defines.push("#define ESM");
  73018. }
  73019. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73020. defines.push("#define DEPTHTEXTURE");
  73021. }
  73022. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73023. var mesh = subMesh.getMesh();
  73024. var material = subMesh.getMaterial();
  73025. // Normal bias.
  73026. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73027. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73028. defines.push("#define NORMAL");
  73029. if (mesh.nonUniformScaling) {
  73030. defines.push("#define NONUNIFORMSCALING");
  73031. }
  73032. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73033. defines.push("#define DIRECTIONINLIGHTDATA");
  73034. }
  73035. }
  73036. // Alpha test
  73037. if (material && material.needAlphaTesting()) {
  73038. var alphaTexture = material.getAlphaTestTexture();
  73039. if (alphaTexture) {
  73040. defines.push("#define ALPHATEST");
  73041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73042. attribs.push(BABYLON.VertexBuffer.UVKind);
  73043. defines.push("#define UV1");
  73044. }
  73045. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73046. if (alphaTexture.coordinatesIndex === 1) {
  73047. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73048. defines.push("#define UV2");
  73049. }
  73050. }
  73051. }
  73052. }
  73053. // Bones
  73054. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73057. if (mesh.numBoneInfluencers > 4) {
  73058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73060. }
  73061. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73062. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  73063. }
  73064. else {
  73065. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73066. }
  73067. // Morph targets
  73068. var manager = mesh.morphTargetManager;
  73069. var morphInfluencers = 0;
  73070. if (manager) {
  73071. if (manager.numInfluencers > 0) {
  73072. defines.push("#define MORPHTARGETS");
  73073. morphInfluencers = manager.numInfluencers;
  73074. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  73075. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  73076. }
  73077. }
  73078. // Instances
  73079. if (useInstances) {
  73080. defines.push("#define INSTANCES");
  73081. attribs.push("world0");
  73082. attribs.push("world1");
  73083. attribs.push("world2");
  73084. attribs.push("world3");
  73085. }
  73086. // Get correct effect
  73087. var join = defines.join("\n");
  73088. if (this._cachedDefines !== join) {
  73089. this._cachedDefines = join;
  73090. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  73091. }
  73092. if (!this._effect.isReady()) {
  73093. return false;
  73094. }
  73095. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73096. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  73097. this._initializeBlurRTTAndPostProcesses();
  73098. }
  73099. }
  73100. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  73101. return false;
  73102. }
  73103. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  73104. return false;
  73105. }
  73106. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  73107. return false;
  73108. }
  73109. return true;
  73110. };
  73111. /**
  73112. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  73113. * @param defines Defines of the material we want to update
  73114. * @param lightIndex Index of the light in the enabled light list of the material
  73115. */
  73116. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  73117. var scene = this._scene;
  73118. var light = this._light;
  73119. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73120. return;
  73121. }
  73122. defines["SHADOW" + lightIndex] = true;
  73123. if (this.useContactHardeningShadow) {
  73124. defines["SHADOWPCSS" + lightIndex] = true;
  73125. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73126. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73127. }
  73128. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73129. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73130. }
  73131. // else default to high.
  73132. }
  73133. if (this.usePercentageCloserFiltering) {
  73134. defines["SHADOWPCF" + lightIndex] = true;
  73135. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73136. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73137. }
  73138. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73139. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73140. }
  73141. // else default to high.
  73142. }
  73143. else if (this.usePoissonSampling) {
  73144. defines["SHADOWPOISSON" + lightIndex] = true;
  73145. }
  73146. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73147. defines["SHADOWESM" + lightIndex] = true;
  73148. }
  73149. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73150. defines["SHADOWCLOSEESM" + lightIndex] = true;
  73151. }
  73152. if (light.needCube()) {
  73153. defines["SHADOWCUBE" + lightIndex] = true;
  73154. }
  73155. };
  73156. /**
  73157. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  73158. * defined in the generator but impacting the effect).
  73159. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  73160. * @param effect The effect we are binfing the information for
  73161. */
  73162. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  73163. var light = this._light;
  73164. var scene = this._scene;
  73165. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73166. return;
  73167. }
  73168. var camera = scene.activeCamera;
  73169. if (!camera) {
  73170. return;
  73171. }
  73172. var shadowMap = this.getShadowMap();
  73173. if (!shadowMap) {
  73174. return;
  73175. }
  73176. if (!light.needCube()) {
  73177. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  73178. }
  73179. // Only PCF uses depth stencil texture.
  73180. if (this._filter === ShadowGenerator.FILTER_PCF) {
  73181. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73182. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73183. }
  73184. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  73185. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73186. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  73187. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73188. }
  73189. else {
  73190. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73191. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  73192. }
  73193. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  73194. };
  73195. /**
  73196. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  73197. * (eq to shadow prjection matrix * light transform matrix)
  73198. * @returns The transform matrix used to create the shadow map
  73199. */
  73200. ShadowGenerator.prototype.getTransformMatrix = function () {
  73201. var scene = this._scene;
  73202. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  73203. return this._transformMatrix;
  73204. }
  73205. this._currentRenderID = scene.getRenderId();
  73206. this._currentFaceIndexCache = this._currentFaceIndex;
  73207. var lightPosition = this._light.position;
  73208. if (this._light.computeTransformedInformation()) {
  73209. lightPosition = this._light.transformedPosition;
  73210. }
  73211. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  73212. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  73213. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  73214. }
  73215. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  73216. this._cachedPosition.copyFrom(lightPosition);
  73217. this._cachedDirection.copyFrom(this._lightDirection);
  73218. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  73219. var shadowMap = this.getShadowMap();
  73220. if (shadowMap) {
  73221. var renderList = shadowMap.renderList;
  73222. if (renderList) {
  73223. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  73224. }
  73225. }
  73226. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  73227. }
  73228. return this._transformMatrix;
  73229. };
  73230. /**
  73231. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  73232. * Cube and 2D textures for instance.
  73233. */
  73234. ShadowGenerator.prototype.recreateShadowMap = function () {
  73235. var shadowMap = this._shadowMap;
  73236. if (!shadowMap) {
  73237. return;
  73238. }
  73239. // Track render list.
  73240. var renderList = shadowMap.renderList;
  73241. // Clean up existing data.
  73242. this._disposeRTTandPostProcesses();
  73243. // Reinitializes.
  73244. this._initializeGenerator();
  73245. // Reaffect the filter to ensure a correct fallback if necessary.
  73246. this.filter = this.filter;
  73247. // Reaffect the filter.
  73248. this._applyFilterValues();
  73249. // Reaffect Render List.
  73250. this._shadowMap.renderList = renderList;
  73251. };
  73252. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  73253. if (this._shadowMap2) {
  73254. this._shadowMap2.dispose();
  73255. this._shadowMap2 = null;
  73256. }
  73257. if (this._boxBlurPostprocess) {
  73258. this._boxBlurPostprocess.dispose();
  73259. this._boxBlurPostprocess = null;
  73260. }
  73261. if (this._kernelBlurXPostprocess) {
  73262. this._kernelBlurXPostprocess.dispose();
  73263. this._kernelBlurXPostprocess = null;
  73264. }
  73265. if (this._kernelBlurYPostprocess) {
  73266. this._kernelBlurYPostprocess.dispose();
  73267. this._kernelBlurYPostprocess = null;
  73268. }
  73269. this._blurPostProcesses = [];
  73270. };
  73271. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  73272. if (this._shadowMap) {
  73273. this._shadowMap.dispose();
  73274. this._shadowMap = null;
  73275. }
  73276. this._disposeBlurPostProcesses();
  73277. };
  73278. /**
  73279. * Disposes the ShadowGenerator.
  73280. * Returns nothing.
  73281. */
  73282. ShadowGenerator.prototype.dispose = function () {
  73283. this._disposeRTTandPostProcesses();
  73284. if (this._light) {
  73285. this._light._shadowGenerator = null;
  73286. this._light._markMeshesAsLightDirty();
  73287. }
  73288. };
  73289. /**
  73290. * Serializes the shadow generator setup to a json object.
  73291. * @returns The serialized JSON object
  73292. */
  73293. ShadowGenerator.prototype.serialize = function () {
  73294. var serializationObject = {};
  73295. var shadowMap = this.getShadowMap();
  73296. if (!shadowMap) {
  73297. return serializationObject;
  73298. }
  73299. serializationObject.lightId = this._light.id;
  73300. serializationObject.mapSize = shadowMap.getRenderSize();
  73301. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73302. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73303. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73304. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73305. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73306. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73307. serializationObject.depthScale = this.depthScale;
  73308. serializationObject.darkness = this.getDarkness();
  73309. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73310. serializationObject.blurKernel = this.blurKernel;
  73311. serializationObject.blurScale = this.blurScale;
  73312. serializationObject.useKernelBlur = this.useKernelBlur;
  73313. serializationObject.transparencyShadow = this._transparencyShadow;
  73314. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73315. serializationObject.bias = this.bias;
  73316. serializationObject.normalBias = this.normalBias;
  73317. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73318. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73319. serializationObject.filteringQuality = this.filteringQuality;
  73320. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73321. serializationObject.renderList = [];
  73322. if (shadowMap.renderList) {
  73323. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73324. var mesh = shadowMap.renderList[meshIndex];
  73325. serializationObject.renderList.push(mesh.id);
  73326. }
  73327. }
  73328. return serializationObject;
  73329. };
  73330. /**
  73331. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73332. * @param parsedShadowGenerator The JSON object to parse
  73333. * @param scene The scene to create the shadow map for
  73334. * @returns The parsed shadow generator
  73335. */
  73336. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73337. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73338. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73339. var shadowMap = shadowGenerator.getShadowMap();
  73340. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73341. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73342. meshes.forEach(function (mesh) {
  73343. if (!shadowMap) {
  73344. return;
  73345. }
  73346. if (!shadowMap.renderList) {
  73347. shadowMap.renderList = [];
  73348. }
  73349. shadowMap.renderList.push(mesh);
  73350. });
  73351. }
  73352. if (parsedShadowGenerator.usePoissonSampling) {
  73353. shadowGenerator.usePoissonSampling = true;
  73354. }
  73355. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73356. shadowGenerator.useExponentialShadowMap = true;
  73357. }
  73358. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73359. shadowGenerator.useBlurExponentialShadowMap = true;
  73360. }
  73361. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73362. shadowGenerator.useCloseExponentialShadowMap = true;
  73363. }
  73364. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73365. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73366. }
  73367. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73368. shadowGenerator.usePercentageCloserFiltering = true;
  73369. }
  73370. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73371. shadowGenerator.useContactHardeningShadow = true;
  73372. }
  73373. if (parsedShadowGenerator.filteringQuality) {
  73374. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73375. }
  73376. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73377. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73378. }
  73379. // Backward compat
  73380. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73381. shadowGenerator.useExponentialShadowMap = true;
  73382. }
  73383. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73384. shadowGenerator.useBlurExponentialShadowMap = true;
  73385. }
  73386. if (parsedShadowGenerator.depthScale) {
  73387. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73388. }
  73389. if (parsedShadowGenerator.blurScale) {
  73390. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73391. }
  73392. if (parsedShadowGenerator.blurBoxOffset) {
  73393. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73394. }
  73395. if (parsedShadowGenerator.useKernelBlur) {
  73396. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73397. }
  73398. if (parsedShadowGenerator.blurKernel) {
  73399. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73400. }
  73401. if (parsedShadowGenerator.bias !== undefined) {
  73402. shadowGenerator.bias = parsedShadowGenerator.bias;
  73403. }
  73404. if (parsedShadowGenerator.normalBias !== undefined) {
  73405. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73406. }
  73407. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73408. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73409. }
  73410. if (parsedShadowGenerator.darkness) {
  73411. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73412. }
  73413. if (parsedShadowGenerator.transparencyShadow) {
  73414. shadowGenerator.setTransparencyShadow(true);
  73415. }
  73416. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73417. return shadowGenerator;
  73418. };
  73419. /**
  73420. * Shadow generator mode None: no filtering applied.
  73421. */
  73422. ShadowGenerator.FILTER_NONE = 0;
  73423. /**
  73424. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73425. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73426. */
  73427. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73428. /**
  73429. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73430. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73431. */
  73432. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73433. /**
  73434. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73435. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73436. */
  73437. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73438. /**
  73439. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73440. * edge artifacts on steep falloff.
  73441. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73442. */
  73443. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73444. /**
  73445. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73446. * edge artifacts on steep falloff.
  73447. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73448. */
  73449. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73450. /**
  73451. * Shadow generator mode PCF: Percentage Closer Filtering
  73452. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73453. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73454. */
  73455. ShadowGenerator.FILTER_PCF = 6;
  73456. /**
  73457. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73458. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73459. * Contact Hardening
  73460. */
  73461. ShadowGenerator.FILTER_PCSS = 7;
  73462. /**
  73463. * Reserved for PCF and PCSS
  73464. * Highest Quality.
  73465. *
  73466. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73467. *
  73468. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73469. */
  73470. ShadowGenerator.QUALITY_HIGH = 0;
  73471. /**
  73472. * Reserved for PCF and PCSS
  73473. * Good tradeoff for quality/perf cross devices
  73474. *
  73475. * Execute PCF on a 3*3 kernel.
  73476. *
  73477. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73478. */
  73479. ShadowGenerator.QUALITY_MEDIUM = 1;
  73480. /**
  73481. * Reserved for PCF and PCSS
  73482. * The lowest quality but the fastest.
  73483. *
  73484. * Execute PCF on a 1*1 kernel.
  73485. *
  73486. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73487. */
  73488. ShadowGenerator.QUALITY_LOW = 2;
  73489. return ShadowGenerator;
  73490. }());
  73491. BABYLON.ShadowGenerator = ShadowGenerator;
  73492. })(BABYLON || (BABYLON = {}));
  73493. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73494. var BABYLON;
  73495. (function (BABYLON) {
  73496. // Adds the parser to the scene parsers.
  73497. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73498. // Shadows
  73499. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73500. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73501. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73502. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73503. // SG would be available on their associated lights
  73504. }
  73505. }
  73506. });
  73507. /**
  73508. * Defines the shadow generator component responsible to manage any shadow generators
  73509. * in a given scene.
  73510. */
  73511. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73512. /**
  73513. * Creates a new instance of the component for the given scene
  73514. * @param scene Defines the scene to register the component in
  73515. */
  73516. function ShadowGeneratorSceneComponent(scene) {
  73517. /**
  73518. * The component name helpfull to identify the component in the list of scene components.
  73519. */
  73520. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73521. this.scene = scene;
  73522. }
  73523. /**
  73524. * Registers the component in a given scene
  73525. */
  73526. ShadowGeneratorSceneComponent.prototype.register = function () {
  73527. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73528. };
  73529. /**
  73530. * Rebuilds the elements related to this component in case of
  73531. * context lost for instance.
  73532. */
  73533. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73534. // Nothing To Do Here.
  73535. };
  73536. /**
  73537. * Serializes the component data to the specified json object
  73538. * @param serializationObject The object to serialize to
  73539. */
  73540. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73541. // Shadows
  73542. serializationObject.shadowGenerators = [];
  73543. var lights = this.scene.lights;
  73544. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73545. var light = lights_1[_i];
  73546. var shadowGenerator = light.getShadowGenerator();
  73547. if (shadowGenerator) {
  73548. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73549. }
  73550. }
  73551. };
  73552. /**
  73553. * Adds all the element from the container to the scene
  73554. * @param container the container holding the elements
  73555. */
  73556. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73557. // Nothing To Do Here. (directly attached to a light)
  73558. };
  73559. /**
  73560. * Removes all the elements in the container from the scene
  73561. * @param container contains the elements to remove
  73562. */
  73563. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73564. // Nothing To Do Here. (directly attached to a light)
  73565. };
  73566. /**
  73567. * Rebuilds the elements related to this component in case of
  73568. * context lost for instance.
  73569. */
  73570. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73571. // Nothing To Do Here.
  73572. };
  73573. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73574. // Shadows
  73575. var scene = this.scene;
  73576. if (this.scene.shadowsEnabled) {
  73577. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73578. var light = scene.lights[lightIndex];
  73579. var shadowGenerator = light.getShadowGenerator();
  73580. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73581. var shadowMap = (shadowGenerator.getShadowMap());
  73582. if (scene.textures.indexOf(shadowMap) !== -1) {
  73583. renderTargets.push(shadowMap);
  73584. }
  73585. }
  73586. }
  73587. }
  73588. };
  73589. return ShadowGeneratorSceneComponent;
  73590. }());
  73591. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73592. })(BABYLON || (BABYLON = {}));
  73593. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73594. var BABYLON;
  73595. (function (BABYLON) {
  73596. var DefaultLoadingScreen = /** @class */ (function () {
  73597. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73598. if (_loadingText === void 0) { _loadingText = ""; }
  73599. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73600. var _this = this;
  73601. this._renderingCanvas = _renderingCanvas;
  73602. this._loadingText = _loadingText;
  73603. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73604. // Resize
  73605. this._resizeLoadingUI = function () {
  73606. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73607. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73608. if (!_this._loadingDiv) {
  73609. return;
  73610. }
  73611. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73612. _this._loadingDiv.style.left = canvasRect.left + "px";
  73613. _this._loadingDiv.style.top = canvasRect.top + "px";
  73614. _this._loadingDiv.style.width = canvasRect.width + "px";
  73615. _this._loadingDiv.style.height = canvasRect.height + "px";
  73616. };
  73617. }
  73618. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73619. if (this._loadingDiv) {
  73620. // Do not add a loading screen if there is already one
  73621. return;
  73622. }
  73623. this._loadingDiv = document.createElement("div");
  73624. this._loadingDiv.id = "babylonjsLoadingDiv";
  73625. this._loadingDiv.style.opacity = "0";
  73626. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73627. this._loadingDiv.style.pointerEvents = "none";
  73628. // Loading text
  73629. this._loadingTextDiv = document.createElement("div");
  73630. this._loadingTextDiv.style.position = "absolute";
  73631. this._loadingTextDiv.style.left = "0";
  73632. this._loadingTextDiv.style.top = "50%";
  73633. this._loadingTextDiv.style.marginTop = "80px";
  73634. this._loadingTextDiv.style.width = "100%";
  73635. this._loadingTextDiv.style.height = "20px";
  73636. this._loadingTextDiv.style.fontFamily = "Arial";
  73637. this._loadingTextDiv.style.fontSize = "14px";
  73638. this._loadingTextDiv.style.color = "white";
  73639. this._loadingTextDiv.style.textAlign = "center";
  73640. this._loadingTextDiv.innerHTML = "Loading";
  73641. this._loadingDiv.appendChild(this._loadingTextDiv);
  73642. //set the predefined text
  73643. this._loadingTextDiv.innerHTML = this._loadingText;
  73644. // Generating keyframes
  73645. var style = document.createElement('style');
  73646. style.type = 'text/css';
  73647. 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 }";
  73648. style.innerHTML = keyFrames;
  73649. document.getElementsByTagName('head')[0].appendChild(style);
  73650. // Loading img
  73651. var imgBack = new Image();
  73652. 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";
  73653. imgBack.style.position = "absolute";
  73654. imgBack.style.left = "50%";
  73655. imgBack.style.top = "50%";
  73656. imgBack.style.marginLeft = "-60px";
  73657. imgBack.style.marginTop = "-60px";
  73658. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73659. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73660. imgBack.style.transformOrigin = "50% 50%";
  73661. imgBack.style.webkitTransformOrigin = "50% 50%";
  73662. this._loadingDiv.appendChild(imgBack);
  73663. this._resizeLoadingUI();
  73664. window.addEventListener("resize", this._resizeLoadingUI);
  73665. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73666. document.body.appendChild(this._loadingDiv);
  73667. this._loadingDiv.style.opacity = "1";
  73668. };
  73669. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73670. var _this = this;
  73671. if (!this._loadingDiv) {
  73672. return;
  73673. }
  73674. var onTransitionEnd = function () {
  73675. if (!_this._loadingDiv) {
  73676. return;
  73677. }
  73678. document.body.removeChild(_this._loadingDiv);
  73679. window.removeEventListener("resize", _this._resizeLoadingUI);
  73680. _this._loadingDiv = null;
  73681. };
  73682. this._loadingDiv.style.opacity = "0";
  73683. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73684. };
  73685. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73686. set: function (text) {
  73687. this._loadingText = text;
  73688. if (this._loadingTextDiv) {
  73689. this._loadingTextDiv.innerHTML = this._loadingText;
  73690. }
  73691. },
  73692. enumerable: true,
  73693. configurable: true
  73694. });
  73695. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73696. get: function () {
  73697. return this._loadingDivBackgroundColor;
  73698. },
  73699. set: function (color) {
  73700. this._loadingDivBackgroundColor = color;
  73701. if (!this._loadingDiv) {
  73702. return;
  73703. }
  73704. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73705. },
  73706. enumerable: true,
  73707. configurable: true
  73708. });
  73709. return DefaultLoadingScreen;
  73710. }());
  73711. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73712. })(BABYLON || (BABYLON = {}));
  73713. //# sourceMappingURL=babylon.loadingScreen.js.map
  73714. var BABYLON;
  73715. (function (BABYLON) {
  73716. var SceneLoaderProgressEvent = /** @class */ (function () {
  73717. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73718. this.lengthComputable = lengthComputable;
  73719. this.loaded = loaded;
  73720. this.total = total;
  73721. }
  73722. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73723. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73724. };
  73725. return SceneLoaderProgressEvent;
  73726. }());
  73727. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73728. var SceneLoader = /** @class */ (function () {
  73729. function SceneLoader() {
  73730. }
  73731. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73732. get: function () {
  73733. return 0;
  73734. },
  73735. enumerable: true,
  73736. configurable: true
  73737. });
  73738. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73739. get: function () {
  73740. return 1;
  73741. },
  73742. enumerable: true,
  73743. configurable: true
  73744. });
  73745. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73746. get: function () {
  73747. return 2;
  73748. },
  73749. enumerable: true,
  73750. configurable: true
  73751. });
  73752. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73753. get: function () {
  73754. return 3;
  73755. },
  73756. enumerable: true,
  73757. configurable: true
  73758. });
  73759. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73760. get: function () {
  73761. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73762. },
  73763. set: function (value) {
  73764. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73765. },
  73766. enumerable: true,
  73767. configurable: true
  73768. });
  73769. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73770. get: function () {
  73771. return SceneLoader._ShowLoadingScreen;
  73772. },
  73773. set: function (value) {
  73774. SceneLoader._ShowLoadingScreen = value;
  73775. },
  73776. enumerable: true,
  73777. configurable: true
  73778. });
  73779. Object.defineProperty(SceneLoader, "loggingLevel", {
  73780. get: function () {
  73781. return SceneLoader._loggingLevel;
  73782. },
  73783. set: function (value) {
  73784. SceneLoader._loggingLevel = value;
  73785. },
  73786. enumerable: true,
  73787. configurable: true
  73788. });
  73789. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73790. get: function () {
  73791. return SceneLoader._CleanBoneMatrixWeights;
  73792. },
  73793. set: function (value) {
  73794. SceneLoader._CleanBoneMatrixWeights = value;
  73795. },
  73796. enumerable: true,
  73797. configurable: true
  73798. });
  73799. SceneLoader._getDefaultPlugin = function () {
  73800. return SceneLoader._registeredPlugins[".babylon"];
  73801. };
  73802. SceneLoader._getPluginForExtension = function (extension) {
  73803. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73804. if (registeredPlugin) {
  73805. return registeredPlugin;
  73806. }
  73807. 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");
  73808. return SceneLoader._getDefaultPlugin();
  73809. };
  73810. SceneLoader._getPluginForDirectLoad = function (data) {
  73811. for (var extension in SceneLoader._registeredPlugins) {
  73812. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73813. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73814. return SceneLoader._registeredPlugins[extension];
  73815. }
  73816. }
  73817. return SceneLoader._getDefaultPlugin();
  73818. };
  73819. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73820. var queryStringPosition = sceneFilename.indexOf("?");
  73821. if (queryStringPosition !== -1) {
  73822. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73823. }
  73824. var dotPosition = sceneFilename.lastIndexOf(".");
  73825. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73826. return SceneLoader._getPluginForExtension(extension);
  73827. };
  73828. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73829. SceneLoader._getDirectLoad = function (sceneFilename) {
  73830. if (sceneFilename.substr(0, 5) === "data:") {
  73831. return sceneFilename.substr(5);
  73832. }
  73833. return null;
  73834. };
  73835. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73836. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73837. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73838. var plugin;
  73839. if (registeredPlugin.plugin.createPlugin) {
  73840. plugin = registeredPlugin.plugin.createPlugin();
  73841. }
  73842. else {
  73843. plugin = registeredPlugin.plugin;
  73844. }
  73845. var useArrayBuffer = registeredPlugin.isBinary;
  73846. var database;
  73847. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73848. var dataCallback = function (data, responseURL) {
  73849. if (scene.isDisposed) {
  73850. onError("Scene has been disposed");
  73851. return;
  73852. }
  73853. scene.database = database;
  73854. onSuccess(plugin, data, responseURL);
  73855. };
  73856. var request = null;
  73857. var pluginDisposed = false;
  73858. var onDisposeObservable = plugin.onDisposeObservable;
  73859. if (onDisposeObservable) {
  73860. onDisposeObservable.add(function () {
  73861. pluginDisposed = true;
  73862. if (request) {
  73863. request.abort();
  73864. request = null;
  73865. }
  73866. onDispose();
  73867. });
  73868. }
  73869. var manifestChecked = function () {
  73870. if (pluginDisposed) {
  73871. return;
  73872. }
  73873. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73874. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73875. } : undefined, database, useArrayBuffer, function (request, exception) {
  73876. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  73877. });
  73878. };
  73879. if (directLoad) {
  73880. dataCallback(directLoad);
  73881. return plugin;
  73882. }
  73883. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73884. var engine = scene.getEngine();
  73885. var canUseOfflineSupport = engine.enableOfflineSupport;
  73886. if (canUseOfflineSupport) {
  73887. // Also check for exceptions
  73888. var exceptionFound = false;
  73889. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73890. var regex = _a[_i];
  73891. if (regex.test(fileInfo.url)) {
  73892. exceptionFound = true;
  73893. break;
  73894. }
  73895. }
  73896. canUseOfflineSupport = !exceptionFound;
  73897. }
  73898. if (canUseOfflineSupport) {
  73899. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73900. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73901. }
  73902. else {
  73903. manifestChecked();
  73904. }
  73905. }
  73906. // Loading file from disk via input file or drag'n'drop
  73907. else {
  73908. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73909. if (file) {
  73910. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73911. }
  73912. else {
  73913. onError("Unable to find file named " + fileInfo.name);
  73914. }
  73915. }
  73916. return plugin;
  73917. };
  73918. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73919. var url;
  73920. var name;
  73921. if (!sceneFilename) {
  73922. url = rootUrl;
  73923. name = BABYLON.Tools.GetFilename(rootUrl);
  73924. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73925. }
  73926. else {
  73927. if (sceneFilename.substr(0, 1) === "/") {
  73928. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73929. return null;
  73930. }
  73931. url = rootUrl + sceneFilename;
  73932. name = sceneFilename;
  73933. }
  73934. ;
  73935. return {
  73936. url: url,
  73937. rootUrl: rootUrl,
  73938. name: name
  73939. };
  73940. };
  73941. // Public functions
  73942. SceneLoader.GetPluginForExtension = function (extension) {
  73943. return SceneLoader._getPluginForExtension(extension).plugin;
  73944. };
  73945. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73946. return !!SceneLoader._registeredPlugins[extension];
  73947. };
  73948. SceneLoader.RegisterPlugin = function (plugin) {
  73949. if (typeof plugin.extensions === "string") {
  73950. var extension = plugin.extensions;
  73951. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73952. plugin: plugin,
  73953. isBinary: false
  73954. };
  73955. }
  73956. else {
  73957. var extensions = plugin.extensions;
  73958. Object.keys(extensions).forEach(function (extension) {
  73959. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73960. plugin: plugin,
  73961. isBinary: extensions[extension].isBinary
  73962. };
  73963. });
  73964. }
  73965. };
  73966. /**
  73967. * Import meshes into a scene
  73968. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73969. * @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)
  73970. * @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)
  73971. * @param scene the instance of BABYLON.Scene to append to
  73972. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73973. * @param onProgress a callback with a progress event for each file being loaded
  73974. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73975. * @param pluginExtension the extension used to determine the plugin
  73976. * @returns The loaded plugin
  73977. */
  73978. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73979. if (sceneFilename === void 0) { sceneFilename = ""; }
  73980. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73981. if (onSuccess === void 0) { onSuccess = null; }
  73982. if (onProgress === void 0) { onProgress = null; }
  73983. if (onError === void 0) { onError = null; }
  73984. if (pluginExtension === void 0) { pluginExtension = null; }
  73985. if (!scene) {
  73986. BABYLON.Tools.Error("No scene available to import mesh to");
  73987. return null;
  73988. }
  73989. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73990. if (!fileInfo) {
  73991. return null;
  73992. }
  73993. var loadingToken = {};
  73994. scene._addPendingData(loadingToken);
  73995. var disposeHandler = function () {
  73996. scene._removePendingData(loadingToken);
  73997. };
  73998. var errorHandler = function (message, exception) {
  73999. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74000. if (onError) {
  74001. onError(scene, errorMessage, exception);
  74002. }
  74003. else {
  74004. BABYLON.Tools.Error(errorMessage);
  74005. // should the exception be thrown?
  74006. }
  74007. disposeHandler();
  74008. };
  74009. var progressHandler = onProgress ? function (event) {
  74010. try {
  74011. onProgress(event);
  74012. }
  74013. catch (e) {
  74014. errorHandler("Error in onProgress callback", e);
  74015. }
  74016. } : undefined;
  74017. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74018. scene.importedMeshesFiles.push(fileInfo.url);
  74019. if (onSuccess) {
  74020. try {
  74021. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74022. }
  74023. catch (e) {
  74024. errorHandler("Error in onSuccess callback", e);
  74025. }
  74026. }
  74027. scene._removePendingData(loadingToken);
  74028. };
  74029. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74030. if (plugin.rewriteRootURL) {
  74031. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74032. }
  74033. if (plugin.importMesh) {
  74034. var syncedPlugin = plugin;
  74035. var meshes = new Array();
  74036. var particleSystems = new Array();
  74037. var skeletons = new Array();
  74038. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  74039. return;
  74040. }
  74041. scene.loadingPluginName = plugin.name;
  74042. successHandler(meshes, particleSystems, skeletons, []);
  74043. }
  74044. else {
  74045. var asyncedPlugin = plugin;
  74046. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  74047. scene.loadingPluginName = plugin.name;
  74048. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  74049. }).catch(function (error) {
  74050. errorHandler(error.message, error);
  74051. });
  74052. }
  74053. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74054. };
  74055. /**
  74056. * Import meshes into a scene
  74057. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74058. * @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)
  74059. * @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)
  74060. * @param scene the instance of BABYLON.Scene to append to
  74061. * @param onProgress a callback with a progress event for each file being loaded
  74062. * @param pluginExtension the extension used to determine the plugin
  74063. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  74064. */
  74065. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74066. if (sceneFilename === void 0) { sceneFilename = ""; }
  74067. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74068. if (onProgress === void 0) { onProgress = null; }
  74069. if (pluginExtension === void 0) { pluginExtension = null; }
  74070. return new Promise(function (resolve, reject) {
  74071. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  74072. resolve({
  74073. meshes: meshes,
  74074. particleSystems: particleSystems,
  74075. skeletons: skeletons,
  74076. animationGroups: animationGroups
  74077. });
  74078. }, onProgress, function (scene, message, exception) {
  74079. reject(exception || new Error(message));
  74080. }, pluginExtension);
  74081. });
  74082. };
  74083. /**
  74084. * Load a scene
  74085. * @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)
  74086. * @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)
  74087. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74088. * @param onSuccess a callback with the scene when import succeeds
  74089. * @param onProgress a callback with a progress event for each file being loaded
  74090. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74091. * @param pluginExtension the extension used to determine the plugin
  74092. * @returns The loaded plugin
  74093. */
  74094. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  74095. if (onSuccess === void 0) { onSuccess = null; }
  74096. if (onProgress === void 0) { onProgress = null; }
  74097. if (onError === void 0) { onError = null; }
  74098. if (pluginExtension === void 0) { pluginExtension = null; }
  74099. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  74100. };
  74101. /**
  74102. * Load a scene
  74103. * @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)
  74104. * @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)
  74105. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74106. * @param onProgress a callback with a progress event for each file being loaded
  74107. * @param pluginExtension the extension used to determine the plugin
  74108. * @returns The loaded scene
  74109. */
  74110. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  74111. if (onProgress === void 0) { onProgress = null; }
  74112. if (pluginExtension === void 0) { pluginExtension = null; }
  74113. return new Promise(function (resolve, reject) {
  74114. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  74115. resolve(scene);
  74116. }, onProgress, function (scene, message, exception) {
  74117. reject(exception || new Error(message));
  74118. }, pluginExtension);
  74119. });
  74120. };
  74121. /**
  74122. * Append a scene
  74123. * @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)
  74124. * @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)
  74125. * @param scene is the instance of BABYLON.Scene to append to
  74126. * @param onSuccess a callback with the scene when import succeeds
  74127. * @param onProgress a callback with a progress event for each file being loaded
  74128. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74129. * @param pluginExtension the extension used to determine the plugin
  74130. * @returns The loaded plugin
  74131. */
  74132. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74133. if (sceneFilename === void 0) { sceneFilename = ""; }
  74134. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74135. if (onSuccess === void 0) { onSuccess = null; }
  74136. if (onProgress === void 0) { onProgress = null; }
  74137. if (onError === void 0) { onError = null; }
  74138. if (pluginExtension === void 0) { pluginExtension = null; }
  74139. if (!scene) {
  74140. BABYLON.Tools.Error("No scene available to append to");
  74141. return null;
  74142. }
  74143. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74144. if (!fileInfo) {
  74145. return null;
  74146. }
  74147. if (SceneLoader.ShowLoadingScreen) {
  74148. scene.getEngine().displayLoadingUI();
  74149. }
  74150. var loadingToken = {};
  74151. scene._addPendingData(loadingToken);
  74152. var disposeHandler = function () {
  74153. scene._removePendingData(loadingToken);
  74154. scene.getEngine().hideLoadingUI();
  74155. };
  74156. var errorHandler = function (message, exception) {
  74157. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  74158. if (onError) {
  74159. onError(scene, errorMessage, exception);
  74160. }
  74161. else {
  74162. BABYLON.Tools.Error(errorMessage);
  74163. // should the exception be thrown?
  74164. }
  74165. disposeHandler();
  74166. };
  74167. var progressHandler = onProgress ? function (event) {
  74168. try {
  74169. onProgress(event);
  74170. }
  74171. catch (e) {
  74172. errorHandler("Error in onProgress callback", e);
  74173. }
  74174. } : undefined;
  74175. var successHandler = function () {
  74176. if (onSuccess) {
  74177. try {
  74178. onSuccess(scene);
  74179. }
  74180. catch (e) {
  74181. errorHandler("Error in onSuccess callback", e);
  74182. }
  74183. }
  74184. scene._removePendingData(loadingToken);
  74185. };
  74186. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74187. if (plugin.load) {
  74188. var syncedPlugin = plugin;
  74189. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  74190. return;
  74191. }
  74192. scene.loadingPluginName = plugin.name;
  74193. successHandler();
  74194. }
  74195. else {
  74196. var asyncedPlugin = plugin;
  74197. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  74198. scene.loadingPluginName = plugin.name;
  74199. successHandler();
  74200. }).catch(function (error) {
  74201. errorHandler(error.message, error);
  74202. });
  74203. }
  74204. if (SceneLoader.ShowLoadingScreen) {
  74205. scene.executeWhenReady(function () {
  74206. scene.getEngine().hideLoadingUI();
  74207. });
  74208. }
  74209. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74210. };
  74211. /**
  74212. * Append a scene
  74213. * @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)
  74214. * @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)
  74215. * @param scene is the instance of BABYLON.Scene to append to
  74216. * @param onProgress a callback with a progress event for each file being loaded
  74217. * @param pluginExtension the extension used to determine the plugin
  74218. * @returns The given scene
  74219. */
  74220. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74221. if (sceneFilename === void 0) { sceneFilename = ""; }
  74222. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74223. if (onProgress === void 0) { onProgress = null; }
  74224. if (pluginExtension === void 0) { pluginExtension = null; }
  74225. return new Promise(function (resolve, reject) {
  74226. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  74227. resolve(scene);
  74228. }, onProgress, function (scene, message, exception) {
  74229. reject(exception || new Error(message));
  74230. }, pluginExtension);
  74231. });
  74232. };
  74233. /**
  74234. * Load a scene into an asset container
  74235. * @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)
  74236. * @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)
  74237. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  74238. * @param onSuccess a callback with the scene when import succeeds
  74239. * @param onProgress a callback with a progress event for each file being loaded
  74240. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74241. * @param pluginExtension the extension used to determine the plugin
  74242. * @returns The loaded plugin
  74243. */
  74244. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74245. if (sceneFilename === void 0) { sceneFilename = ""; }
  74246. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74247. if (onSuccess === void 0) { onSuccess = null; }
  74248. if (onProgress === void 0) { onProgress = null; }
  74249. if (onError === void 0) { onError = null; }
  74250. if (pluginExtension === void 0) { pluginExtension = null; }
  74251. if (!scene) {
  74252. BABYLON.Tools.Error("No scene available to load asset container to");
  74253. return null;
  74254. }
  74255. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74256. if (!fileInfo) {
  74257. return null;
  74258. }
  74259. var loadingToken = {};
  74260. scene._addPendingData(loadingToken);
  74261. var disposeHandler = function () {
  74262. scene._removePendingData(loadingToken);
  74263. };
  74264. var errorHandler = function (message, exception) {
  74265. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  74266. if (onError) {
  74267. onError(scene, errorMessage, exception);
  74268. }
  74269. else {
  74270. BABYLON.Tools.Error(errorMessage);
  74271. // should the exception be thrown?
  74272. }
  74273. disposeHandler();
  74274. };
  74275. var progressHandler = onProgress ? function (event) {
  74276. try {
  74277. onProgress(event);
  74278. }
  74279. catch (e) {
  74280. errorHandler("Error in onProgress callback", e);
  74281. }
  74282. } : undefined;
  74283. var successHandler = function (assets) {
  74284. if (onSuccess) {
  74285. try {
  74286. onSuccess(assets);
  74287. }
  74288. catch (e) {
  74289. errorHandler("Error in onSuccess callback", e);
  74290. }
  74291. }
  74292. scene._removePendingData(loadingToken);
  74293. };
  74294. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74295. if (plugin.loadAssetContainer) {
  74296. var syncedPlugin = plugin;
  74297. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74298. if (!assetContainer) {
  74299. return;
  74300. }
  74301. scene.loadingPluginName = plugin.name;
  74302. successHandler(assetContainer);
  74303. }
  74304. else if (plugin.loadAssetContainerAsync) {
  74305. var asyncedPlugin = plugin;
  74306. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74307. scene.loadingPluginName = plugin.name;
  74308. successHandler(assetContainer);
  74309. }).catch(function (error) {
  74310. errorHandler(error.message, error);
  74311. });
  74312. }
  74313. else {
  74314. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74315. }
  74316. if (SceneLoader.ShowLoadingScreen) {
  74317. scene.executeWhenReady(function () {
  74318. scene.getEngine().hideLoadingUI();
  74319. });
  74320. }
  74321. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74322. };
  74323. /**
  74324. * Load a scene into an asset container
  74325. * @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)
  74326. * @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)
  74327. * @param scene is the instance of BABYLON.Scene to append to
  74328. * @param onProgress a callback with a progress event for each file being loaded
  74329. * @param pluginExtension the extension used to determine the plugin
  74330. * @returns The loaded asset container
  74331. */
  74332. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74333. if (sceneFilename === void 0) { sceneFilename = ""; }
  74334. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74335. if (onProgress === void 0) { onProgress = null; }
  74336. if (pluginExtension === void 0) { pluginExtension = null; }
  74337. return new Promise(function (resolve, reject) {
  74338. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74339. resolve(assetContainer);
  74340. }, onProgress, function (scene, message, exception) {
  74341. reject(exception || new Error(message));
  74342. }, pluginExtension);
  74343. });
  74344. };
  74345. // Flags
  74346. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74347. SceneLoader._ShowLoadingScreen = true;
  74348. SceneLoader._CleanBoneMatrixWeights = false;
  74349. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74350. // Members
  74351. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74352. SceneLoader._registeredPlugins = {};
  74353. return SceneLoader;
  74354. }());
  74355. BABYLON.SceneLoader = SceneLoader;
  74356. ;
  74357. })(BABYLON || (BABYLON = {}));
  74358. //# sourceMappingURL=babylon.sceneLoader.js.map
  74359. var BABYLON;
  74360. (function (BABYLON) {
  74361. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74362. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74363. var parsedMaterial = parsedData.materials[index];
  74364. if (parsedMaterial.id === id) {
  74365. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74366. }
  74367. }
  74368. return null;
  74369. };
  74370. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74371. for (var i in names) {
  74372. if (mesh.name === names[i]) {
  74373. hierarchyIds.push(mesh.id);
  74374. return true;
  74375. }
  74376. }
  74377. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74378. hierarchyIds.push(mesh.id);
  74379. return true;
  74380. }
  74381. return false;
  74382. };
  74383. var logOperation = function (operation, producer) {
  74384. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74385. };
  74386. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74387. if (addToScene === void 0) { addToScene = false; }
  74388. var container = new BABYLON.AssetContainer(scene);
  74389. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74390. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74391. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74392. // and avoid problems with multiple concurrent .babylon loads.
  74393. var log = "importScene has failed JSON parse";
  74394. try {
  74395. var parsedData = JSON.parse(data);
  74396. log = "";
  74397. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74398. var index;
  74399. var cache;
  74400. // Lights
  74401. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74402. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74403. var parsedLight = parsedData.lights[index];
  74404. var light = BABYLON.Light.Parse(parsedLight, scene);
  74405. if (light) {
  74406. container.lights.push(light);
  74407. log += (index === 0 ? "\n\tLights:" : "");
  74408. log += "\n\t\t" + light.toString(fullDetails);
  74409. }
  74410. }
  74411. }
  74412. // Animations
  74413. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74414. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74415. var parsedAnimation = parsedData.animations[index];
  74416. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74417. scene.animations.push(animation);
  74418. container.animations.push(animation);
  74419. log += (index === 0 ? "\n\tAnimations:" : "");
  74420. log += "\n\t\t" + animation.toString(fullDetails);
  74421. }
  74422. }
  74423. // Materials
  74424. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74425. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74426. var parsedMaterial = parsedData.materials[index];
  74427. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74428. container.materials.push(mat);
  74429. log += (index === 0 ? "\n\tMaterials:" : "");
  74430. log += "\n\t\t" + mat.toString(fullDetails);
  74431. }
  74432. }
  74433. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74434. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74435. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74436. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74437. container.multiMaterials.push(mmat);
  74438. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74439. log += "\n\t\t" + mmat.toString(fullDetails);
  74440. }
  74441. }
  74442. // Morph targets
  74443. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74444. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74445. var managerData = _a[_i];
  74446. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74447. }
  74448. }
  74449. // Skeletons
  74450. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74451. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74452. var parsedSkeleton = parsedData.skeletons[index];
  74453. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74454. container.skeletons.push(skeleton);
  74455. log += (index === 0 ? "\n\tSkeletons:" : "");
  74456. log += "\n\t\t" + skeleton.toString(fullDetails);
  74457. }
  74458. }
  74459. // Geometries
  74460. var geometries = parsedData.geometries;
  74461. if (geometries !== undefined && geometries !== null) {
  74462. var addedGeometry = new Array();
  74463. // Boxes
  74464. var boxes = geometries.boxes;
  74465. if (boxes !== undefined && boxes !== null) {
  74466. for (index = 0, cache = boxes.length; index < cache; index++) {
  74467. var parsedBox = boxes[index];
  74468. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74469. }
  74470. }
  74471. // Spheres
  74472. var spheres = geometries.spheres;
  74473. if (spheres !== undefined && spheres !== null) {
  74474. for (index = 0, cache = spheres.length; index < cache; index++) {
  74475. var parsedSphere = spheres[index];
  74476. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74477. }
  74478. }
  74479. // Cylinders
  74480. var cylinders = geometries.cylinders;
  74481. if (cylinders !== undefined && cylinders !== null) {
  74482. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74483. var parsedCylinder = cylinders[index];
  74484. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74485. }
  74486. }
  74487. // Toruses
  74488. var toruses = geometries.toruses;
  74489. if (toruses !== undefined && toruses !== null) {
  74490. for (index = 0, cache = toruses.length; index < cache; index++) {
  74491. var parsedTorus = toruses[index];
  74492. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74493. }
  74494. }
  74495. // Grounds
  74496. var grounds = geometries.grounds;
  74497. if (grounds !== undefined && grounds !== null) {
  74498. for (index = 0, cache = grounds.length; index < cache; index++) {
  74499. var parsedGround = grounds[index];
  74500. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74501. }
  74502. }
  74503. // Planes
  74504. var planes = geometries.planes;
  74505. if (planes !== undefined && planes !== null) {
  74506. for (index = 0, cache = planes.length; index < cache; index++) {
  74507. var parsedPlane = planes[index];
  74508. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74509. }
  74510. }
  74511. // TorusKnots
  74512. var torusKnots = geometries.torusKnots;
  74513. if (torusKnots !== undefined && torusKnots !== null) {
  74514. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74515. var parsedTorusKnot = torusKnots[index];
  74516. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74517. }
  74518. }
  74519. // VertexData
  74520. var vertexData = geometries.vertexData;
  74521. if (vertexData !== undefined && vertexData !== null) {
  74522. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74523. var parsedVertexData = vertexData[index];
  74524. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74525. }
  74526. }
  74527. addedGeometry.forEach(function (g) {
  74528. if (g) {
  74529. container.geometries.push(g);
  74530. }
  74531. });
  74532. }
  74533. // Transform nodes
  74534. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74535. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74536. var parsedTransformNode = parsedData.transformNodes[index];
  74537. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74538. container.transformNodes.push(node);
  74539. }
  74540. }
  74541. // Meshes
  74542. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74543. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74544. var parsedMesh = parsedData.meshes[index];
  74545. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74546. container.meshes.push(mesh);
  74547. log += (index === 0 ? "\n\tMeshes:" : "");
  74548. log += "\n\t\t" + mesh.toString(fullDetails);
  74549. }
  74550. }
  74551. // Cameras
  74552. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74553. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74554. var parsedCamera = parsedData.cameras[index];
  74555. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74556. container.cameras.push(camera);
  74557. log += (index === 0 ? "\n\tCameras:" : "");
  74558. log += "\n\t\t" + camera.toString(fullDetails);
  74559. }
  74560. }
  74561. // Animation Groups
  74562. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74563. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74564. var parsedAnimationGroup = parsedData.animationGroups[index];
  74565. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74566. container.animationGroups.push(animationGroup);
  74567. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74568. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74569. }
  74570. }
  74571. // Browsing all the graph to connect the dots
  74572. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74573. var camera = scene.cameras[index];
  74574. if (camera._waitingParentId) {
  74575. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74576. camera._waitingParentId = null;
  74577. }
  74578. }
  74579. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74580. var light_1 = scene.lights[index];
  74581. if (light_1 && light_1._waitingParentId) {
  74582. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74583. light_1._waitingParentId = null;
  74584. }
  74585. }
  74586. // Connect parents & children and parse actions
  74587. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74588. var transformNode = scene.transformNodes[index];
  74589. if (transformNode._waitingParentId) {
  74590. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74591. transformNode._waitingParentId = null;
  74592. }
  74593. }
  74594. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74595. var mesh = scene.meshes[index];
  74596. if (mesh._waitingParentId) {
  74597. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74598. mesh._waitingParentId = null;
  74599. }
  74600. }
  74601. // freeze world matrix application
  74602. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74603. var currentMesh = scene.meshes[index];
  74604. if (currentMesh._waitingFreezeWorldMatrix) {
  74605. currentMesh.freezeWorldMatrix();
  74606. currentMesh._waitingFreezeWorldMatrix = null;
  74607. }
  74608. else {
  74609. currentMesh.computeWorldMatrix(true);
  74610. }
  74611. }
  74612. // Lights exclusions / inclusions
  74613. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74614. var light_2 = scene.lights[index];
  74615. // Excluded check
  74616. if (light_2._excludedMeshesIds.length > 0) {
  74617. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74618. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74619. if (excludedMesh) {
  74620. light_2.excludedMeshes.push(excludedMesh);
  74621. }
  74622. }
  74623. light_2._excludedMeshesIds = [];
  74624. }
  74625. // Included check
  74626. if (light_2._includedOnlyMeshesIds.length > 0) {
  74627. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74628. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74629. if (includedOnlyMesh) {
  74630. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74631. }
  74632. }
  74633. light_2._includedOnlyMeshesIds = [];
  74634. }
  74635. }
  74636. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74637. // Actions (scene) Done last as it can access other objects.
  74638. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74639. var mesh = scene.meshes[index];
  74640. if (mesh._waitingActions) {
  74641. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74642. mesh._waitingActions = null;
  74643. }
  74644. }
  74645. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74646. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74647. }
  74648. if (!addToScene) {
  74649. container.removeAllFromScene();
  74650. }
  74651. }
  74652. catch (err) {
  74653. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74654. if (onError) {
  74655. onError(msg, err);
  74656. }
  74657. else {
  74658. BABYLON.Tools.Log(msg);
  74659. throw err;
  74660. }
  74661. }
  74662. finally {
  74663. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74664. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74665. }
  74666. }
  74667. return container;
  74668. };
  74669. BABYLON.SceneLoader.RegisterPlugin({
  74670. name: "babylon.js",
  74671. extensions: ".babylon",
  74672. canDirectLoad: function (data) {
  74673. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74674. return true;
  74675. }
  74676. return false;
  74677. },
  74678. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74679. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74680. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74681. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74682. // and avoid problems with multiple concurrent .babylon loads.
  74683. var log = "importMesh has failed JSON parse";
  74684. try {
  74685. var parsedData = JSON.parse(data);
  74686. log = "";
  74687. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74688. if (!meshesNames) {
  74689. meshesNames = null;
  74690. }
  74691. else if (!Array.isArray(meshesNames)) {
  74692. meshesNames = [meshesNames];
  74693. }
  74694. var hierarchyIds = new Array();
  74695. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74696. var loadedSkeletonsIds = [];
  74697. var loadedMaterialsIds = [];
  74698. var index;
  74699. var cache;
  74700. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74701. var parsedMesh = parsedData.meshes[index];
  74702. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74703. if (meshesNames !== null) {
  74704. // Remove found mesh name from list.
  74705. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74706. }
  74707. //Geometry?
  74708. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74709. //does the file contain geometries?
  74710. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74711. //find the correct geometry and add it to the scene
  74712. var found = false;
  74713. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74714. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74715. return;
  74716. }
  74717. else {
  74718. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74719. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74720. switch (geometryType) {
  74721. case "boxes":
  74722. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74723. break;
  74724. case "spheres":
  74725. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74726. break;
  74727. case "cylinders":
  74728. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74729. break;
  74730. case "toruses":
  74731. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74732. break;
  74733. case "grounds":
  74734. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74735. break;
  74736. case "planes":
  74737. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74738. break;
  74739. case "torusKnots":
  74740. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74741. break;
  74742. case "vertexData":
  74743. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74744. break;
  74745. }
  74746. found = true;
  74747. }
  74748. });
  74749. }
  74750. });
  74751. if (found === false) {
  74752. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74753. }
  74754. }
  74755. }
  74756. // Material ?
  74757. if (parsedMesh.materialId) {
  74758. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74759. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74760. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74761. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74762. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74763. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74764. var subMatId = parsedMultiMaterial.materials[matIndex];
  74765. loadedMaterialsIds.push(subMatId);
  74766. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74767. if (mat) {
  74768. log += "\n\tMaterial " + mat.toString(fullDetails);
  74769. }
  74770. }
  74771. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74772. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74773. if (mmat) {
  74774. materialFound = true;
  74775. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74776. }
  74777. break;
  74778. }
  74779. }
  74780. }
  74781. if (materialFound === false) {
  74782. loadedMaterialsIds.push(parsedMesh.materialId);
  74783. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74784. if (!mat) {
  74785. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74786. }
  74787. else {
  74788. log += "\n\tMaterial " + mat.toString(fullDetails);
  74789. }
  74790. }
  74791. }
  74792. // Skeleton ?
  74793. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74794. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74795. if (skeletonAlreadyLoaded === false) {
  74796. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74797. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74798. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74799. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74800. skeletons.push(skeleton);
  74801. loadedSkeletonsIds.push(parsedSkeleton.id);
  74802. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74803. }
  74804. }
  74805. }
  74806. }
  74807. // Morph targets ?
  74808. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74809. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74810. var managerData = _a[_i];
  74811. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74812. }
  74813. }
  74814. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74815. meshes.push(mesh);
  74816. log += "\n\tMesh " + mesh.toString(fullDetails);
  74817. }
  74818. }
  74819. // Connecting parents
  74820. var currentMesh;
  74821. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74822. currentMesh = scene.meshes[index];
  74823. if (currentMesh._waitingParentId) {
  74824. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74825. currentMesh._waitingParentId = null;
  74826. }
  74827. }
  74828. // freeze and compute world matrix application
  74829. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74830. currentMesh = scene.meshes[index];
  74831. if (currentMesh._waitingFreezeWorldMatrix) {
  74832. currentMesh.freezeWorldMatrix();
  74833. currentMesh._waitingFreezeWorldMatrix = null;
  74834. }
  74835. else {
  74836. currentMesh.computeWorldMatrix(true);
  74837. }
  74838. }
  74839. }
  74840. // Particles
  74841. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74842. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74843. if (parser) {
  74844. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74845. var parsedParticleSystem = parsedData.particleSystems[index];
  74846. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74847. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74848. }
  74849. }
  74850. }
  74851. }
  74852. return true;
  74853. }
  74854. catch (err) {
  74855. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74856. if (onError) {
  74857. onError(msg, err);
  74858. }
  74859. else {
  74860. BABYLON.Tools.Log(msg);
  74861. throw err;
  74862. }
  74863. }
  74864. finally {
  74865. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74866. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74867. }
  74868. }
  74869. return false;
  74870. },
  74871. load: function (scene, data, rootUrl, onError) {
  74872. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74873. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74874. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74875. // and avoid problems with multiple concurrent .babylon loads.
  74876. var log = "importScene has failed JSON parse";
  74877. try {
  74878. var parsedData = JSON.parse(data);
  74879. log = "";
  74880. // Scene
  74881. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74882. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74883. }
  74884. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74885. scene.autoClear = parsedData.autoClear;
  74886. }
  74887. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74888. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74889. }
  74890. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74891. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74892. }
  74893. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74894. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74895. }
  74896. // Fog
  74897. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74898. scene.fogMode = parsedData.fogMode;
  74899. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74900. scene.fogStart = parsedData.fogStart;
  74901. scene.fogEnd = parsedData.fogEnd;
  74902. scene.fogDensity = parsedData.fogDensity;
  74903. log += "\tFog mode for scene: ";
  74904. switch (scene.fogMode) {
  74905. // getters not compiling, so using hardcoded
  74906. case 1:
  74907. log += "exp\n";
  74908. break;
  74909. case 2:
  74910. log += "exp2\n";
  74911. break;
  74912. case 3:
  74913. log += "linear\n";
  74914. break;
  74915. }
  74916. }
  74917. //Physics
  74918. if (parsedData.physicsEnabled) {
  74919. var physicsPlugin;
  74920. if (parsedData.physicsEngine === "cannon") {
  74921. physicsPlugin = new BABYLON.CannonJSPlugin();
  74922. }
  74923. else if (parsedData.physicsEngine === "oimo") {
  74924. physicsPlugin = new BABYLON.OimoJSPlugin();
  74925. }
  74926. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74927. //else - default engine, which is currently oimo
  74928. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74929. scene.enablePhysics(physicsGravity, physicsPlugin);
  74930. }
  74931. // Metadata
  74932. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74933. scene.metadata = parsedData.metadata;
  74934. }
  74935. //collisions, if defined. otherwise, default is true
  74936. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74937. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74938. }
  74939. scene.workerCollisions = !!parsedData.workerCollisions;
  74940. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74941. if (!container) {
  74942. return false;
  74943. }
  74944. if (parsedData.autoAnimate) {
  74945. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74946. }
  74947. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74948. scene.setActiveCameraByID(parsedData.activeCameraID);
  74949. }
  74950. // Environment texture
  74951. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74952. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74953. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74954. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74955. if (parsedData.environmentTextureRotationY) {
  74956. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74957. }
  74958. scene.environmentTexture = hdrTexture;
  74959. }
  74960. else {
  74961. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74962. if (parsedData.environmentTextureRotationY) {
  74963. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74964. }
  74965. scene.environmentTexture = cubeTexture;
  74966. }
  74967. if (parsedData.createDefaultSkybox === true) {
  74968. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74969. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74970. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74971. }
  74972. }
  74973. // Finish
  74974. return true;
  74975. }
  74976. catch (err) {
  74977. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  74978. if (onError) {
  74979. onError(msg, err);
  74980. }
  74981. else {
  74982. BABYLON.Tools.Log(msg);
  74983. throw err;
  74984. }
  74985. }
  74986. finally {
  74987. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74988. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74989. }
  74990. }
  74991. return false;
  74992. },
  74993. loadAssetContainer: function (scene, data, rootUrl, onError) {
  74994. var container = loadAssetContainer(scene, data, rootUrl, onError);
  74995. return container;
  74996. }
  74997. });
  74998. })(BABYLON || (BABYLON = {}));
  74999. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75000. var BABYLON;
  75001. (function (BABYLON) {
  75002. var FilesInput = /** @class */ (function () {
  75003. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75004. this.onProcessFileCallback = function () { return true; };
  75005. this._engine = engine;
  75006. this._currentScene = scene;
  75007. this._sceneLoadedCallback = sceneLoadedCallback;
  75008. this._progressCallback = progressCallback;
  75009. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75010. this._textureLoadingCallback = textureLoadingCallback;
  75011. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75012. this._onReloadCallback = onReloadCallback;
  75013. this._errorCallback = errorCallback;
  75014. }
  75015. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  75016. var _this = this;
  75017. if (elementToMonitor) {
  75018. this._elementToMonitor = elementToMonitor;
  75019. this._dragEnterHandler = function (e) { _this.drag(e); };
  75020. this._dragOverHandler = function (e) { _this.drag(e); };
  75021. this._dropHandler = function (e) { _this.drop(e); };
  75022. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  75023. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  75024. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  75025. }
  75026. };
  75027. FilesInput.prototype.dispose = function () {
  75028. if (!this._elementToMonitor) {
  75029. return;
  75030. }
  75031. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  75032. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  75033. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  75034. };
  75035. FilesInput.prototype.renderFunction = function () {
  75036. if (this._additionalRenderLoopLogicCallback) {
  75037. this._additionalRenderLoopLogicCallback();
  75038. }
  75039. if (this._currentScene) {
  75040. if (this._textureLoadingCallback) {
  75041. var remaining = this._currentScene.getWaitingItemsCount();
  75042. if (remaining > 0) {
  75043. this._textureLoadingCallback(remaining);
  75044. }
  75045. }
  75046. this._currentScene.render();
  75047. }
  75048. };
  75049. FilesInput.prototype.drag = function (e) {
  75050. e.stopPropagation();
  75051. e.preventDefault();
  75052. };
  75053. FilesInput.prototype.drop = function (eventDrop) {
  75054. eventDrop.stopPropagation();
  75055. eventDrop.preventDefault();
  75056. this.loadFiles(eventDrop);
  75057. };
  75058. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  75059. var _this = this;
  75060. var reader = folder.createReader();
  75061. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  75062. reader.readEntries(function (entries) {
  75063. remaining.count += entries.length;
  75064. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  75065. var entry = entries_1[_i];
  75066. if (entry.isFile) {
  75067. entry.file(function (file) {
  75068. file.correctName = relativePath + file.name;
  75069. files.push(file);
  75070. if (--remaining.count === 0) {
  75071. callback();
  75072. }
  75073. });
  75074. }
  75075. else if (entry.isDirectory) {
  75076. _this._traverseFolder(entry, files, remaining, callback);
  75077. }
  75078. }
  75079. if (--remaining.count) {
  75080. callback();
  75081. }
  75082. });
  75083. };
  75084. FilesInput.prototype._processFiles = function (files) {
  75085. for (var i = 0; i < files.length; i++) {
  75086. var name = files[i].correctName.toLowerCase();
  75087. var extension = name.split('.').pop();
  75088. if (!this.onProcessFileCallback(files[i], name, extension)) {
  75089. continue;
  75090. }
  75091. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  75092. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  75093. this._sceneFileToLoad = files[i];
  75094. }
  75095. FilesInput.FilesToLoad[name] = files[i];
  75096. }
  75097. };
  75098. FilesInput.prototype.loadFiles = function (event) {
  75099. var _this = this;
  75100. // Handling data transfer via drag'n'drop
  75101. if (event && event.dataTransfer && event.dataTransfer.files) {
  75102. this._filesToLoad = event.dataTransfer.files;
  75103. }
  75104. // Handling files from input files
  75105. if (event && event.target && event.target.files) {
  75106. this._filesToLoad = event.target.files;
  75107. }
  75108. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  75109. return;
  75110. }
  75111. if (this._startingProcessingFilesCallback) {
  75112. this._startingProcessingFilesCallback(this._filesToLoad);
  75113. }
  75114. if (this._filesToLoad && this._filesToLoad.length > 0) {
  75115. var files_1 = new Array();
  75116. var folders = [];
  75117. var items = event.dataTransfer ? event.dataTransfer.items : null;
  75118. for (var i = 0; i < this._filesToLoad.length; i++) {
  75119. var fileToLoad = this._filesToLoad[i];
  75120. var name_1 = fileToLoad.name.toLowerCase();
  75121. var entry = void 0;
  75122. fileToLoad.correctName = name_1;
  75123. if (items) {
  75124. var item = items[i];
  75125. if (item.getAsEntry) {
  75126. entry = item.getAsEntry();
  75127. }
  75128. else if (item.webkitGetAsEntry) {
  75129. entry = item.webkitGetAsEntry();
  75130. }
  75131. }
  75132. if (!entry) {
  75133. files_1.push(fileToLoad);
  75134. }
  75135. else {
  75136. if (entry.isDirectory) {
  75137. folders.push(entry);
  75138. }
  75139. else {
  75140. files_1.push(fileToLoad);
  75141. }
  75142. }
  75143. }
  75144. if (folders.length === 0) {
  75145. this._processFiles(files_1);
  75146. this._processReload();
  75147. }
  75148. else {
  75149. var remaining = { count: folders.length };
  75150. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  75151. var folder = folders_1[_i];
  75152. this._traverseFolder(folder, files_1, remaining, function () {
  75153. _this._processFiles(files_1);
  75154. if (remaining.count === 0) {
  75155. _this._processReload();
  75156. }
  75157. });
  75158. }
  75159. }
  75160. }
  75161. };
  75162. FilesInput.prototype._processReload = function () {
  75163. if (this._onReloadCallback) {
  75164. this._onReloadCallback(this._sceneFileToLoad);
  75165. }
  75166. else {
  75167. this.reload();
  75168. }
  75169. };
  75170. FilesInput.prototype.reload = function () {
  75171. var _this = this;
  75172. // If a scene file has been provided
  75173. if (this._sceneFileToLoad) {
  75174. if (this._currentScene) {
  75175. if (BABYLON.Tools.errorsCount > 0) {
  75176. BABYLON.Tools.ClearLogCache();
  75177. }
  75178. this._engine.stopRenderLoop();
  75179. }
  75180. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  75181. if (_this._progressCallback) {
  75182. _this._progressCallback(progress);
  75183. }
  75184. }).then(function (scene) {
  75185. if (_this._currentScene) {
  75186. _this._currentScene.dispose();
  75187. }
  75188. _this._currentScene = scene;
  75189. if (_this._sceneLoadedCallback) {
  75190. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  75191. }
  75192. // Wait for textures and shaders to be ready
  75193. _this._currentScene.executeWhenReady(function () {
  75194. _this._engine.runRenderLoop(function () {
  75195. _this.renderFunction();
  75196. });
  75197. });
  75198. }).catch(function (error) {
  75199. if (_this._errorCallback) {
  75200. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  75201. }
  75202. });
  75203. }
  75204. else {
  75205. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  75206. }
  75207. };
  75208. FilesInput.FilesToLoad = {};
  75209. return FilesInput;
  75210. }());
  75211. BABYLON.FilesInput = FilesInput;
  75212. })(BABYLON || (BABYLON = {}));
  75213. //# sourceMappingURL=babylon.filesInput.js.map
  75214. var BABYLON;
  75215. (function (BABYLON) {
  75216. var Tags = /** @class */ (function () {
  75217. function Tags() {
  75218. }
  75219. Tags.EnableFor = function (obj) {
  75220. obj._tags = obj._tags || {};
  75221. obj.hasTags = function () {
  75222. return Tags.HasTags(obj);
  75223. };
  75224. obj.addTags = function (tagsString) {
  75225. return Tags.AddTagsTo(obj, tagsString);
  75226. };
  75227. obj.removeTags = function (tagsString) {
  75228. return Tags.RemoveTagsFrom(obj, tagsString);
  75229. };
  75230. obj.matchesTagsQuery = function (tagsQuery) {
  75231. return Tags.MatchesQuery(obj, tagsQuery);
  75232. };
  75233. };
  75234. Tags.DisableFor = function (obj) {
  75235. delete obj._tags;
  75236. delete obj.hasTags;
  75237. delete obj.addTags;
  75238. delete obj.removeTags;
  75239. delete obj.matchesTagsQuery;
  75240. };
  75241. Tags.HasTags = function (obj) {
  75242. if (!obj._tags) {
  75243. return false;
  75244. }
  75245. return !BABYLON.Tools.IsEmpty(obj._tags);
  75246. };
  75247. Tags.GetTags = function (obj, asString) {
  75248. if (asString === void 0) { asString = true; }
  75249. if (!obj._tags) {
  75250. return null;
  75251. }
  75252. if (asString) {
  75253. var tagsArray = [];
  75254. for (var tag in obj._tags) {
  75255. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  75256. tagsArray.push(tag);
  75257. }
  75258. }
  75259. return tagsArray.join(" ");
  75260. }
  75261. else {
  75262. return obj._tags;
  75263. }
  75264. };
  75265. // the tags 'true' and 'false' are reserved and cannot be used as tags
  75266. // a tag cannot start with '||', '&&', and '!'
  75267. // it cannot contain whitespaces
  75268. Tags.AddTagsTo = function (obj, tagsString) {
  75269. if (!tagsString) {
  75270. return;
  75271. }
  75272. if (typeof tagsString !== "string") {
  75273. return;
  75274. }
  75275. var tags = tagsString.split(" ");
  75276. tags.forEach(function (tag, index, array) {
  75277. Tags._AddTagTo(obj, tag);
  75278. });
  75279. };
  75280. Tags._AddTagTo = function (obj, tag) {
  75281. tag = tag.trim();
  75282. if (tag === "" || tag === "true" || tag === "false") {
  75283. return;
  75284. }
  75285. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  75286. return;
  75287. }
  75288. Tags.EnableFor(obj);
  75289. obj._tags[tag] = true;
  75290. };
  75291. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75292. if (!Tags.HasTags(obj)) {
  75293. return;
  75294. }
  75295. var tags = tagsString.split(" ");
  75296. for (var t in tags) {
  75297. Tags._RemoveTagFrom(obj, tags[t]);
  75298. }
  75299. };
  75300. Tags._RemoveTagFrom = function (obj, tag) {
  75301. delete obj._tags[tag];
  75302. };
  75303. Tags.MatchesQuery = function (obj, tagsQuery) {
  75304. if (tagsQuery === undefined) {
  75305. return true;
  75306. }
  75307. if (tagsQuery === "") {
  75308. return Tags.HasTags(obj);
  75309. }
  75310. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75311. };
  75312. return Tags;
  75313. }());
  75314. BABYLON.Tags = Tags;
  75315. })(BABYLON || (BABYLON = {}));
  75316. //# sourceMappingURL=babylon.tags.js.map
  75317. var BABYLON;
  75318. (function (BABYLON) {
  75319. /**
  75320. * Class used to evalaute queries containing `and` and `or` operators
  75321. */
  75322. var AndOrNotEvaluator = /** @class */ (function () {
  75323. function AndOrNotEvaluator() {
  75324. }
  75325. /**
  75326. * Evaluate a query
  75327. * @param query defines the query to evaluate
  75328. * @param evaluateCallback defines the callback used to filter result
  75329. * @returns true if the query matches
  75330. */
  75331. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75332. if (!query.match(/\([^\(\)]*\)/g)) {
  75333. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75334. }
  75335. else {
  75336. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75337. // remove parenthesis
  75338. r = r.slice(1, r.length - 1);
  75339. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75340. });
  75341. }
  75342. if (query === "true") {
  75343. return true;
  75344. }
  75345. if (query === "false") {
  75346. return false;
  75347. }
  75348. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75349. };
  75350. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75351. evaluateCallback = evaluateCallback || (function (r) {
  75352. return r === "true" ? true : false;
  75353. });
  75354. var result;
  75355. var or = parenthesisContent.split("||");
  75356. for (var i in or) {
  75357. if (or.hasOwnProperty(i)) {
  75358. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75359. var and = ori.split("&&");
  75360. if (and.length > 1) {
  75361. for (var j = 0; j < and.length; ++j) {
  75362. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75363. if (andj !== "true" && andj !== "false") {
  75364. if (andj[0] === "!") {
  75365. result = !evaluateCallback(andj.substring(1));
  75366. }
  75367. else {
  75368. result = evaluateCallback(andj);
  75369. }
  75370. }
  75371. else {
  75372. result = andj === "true" ? true : false;
  75373. }
  75374. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75375. ori = "false";
  75376. break;
  75377. }
  75378. }
  75379. }
  75380. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75381. result = true;
  75382. break;
  75383. }
  75384. // result equals false (or undefined)
  75385. if (ori !== "true" && ori !== "false") {
  75386. if (ori[0] === "!") {
  75387. result = !evaluateCallback(ori.substring(1));
  75388. }
  75389. else {
  75390. result = evaluateCallback(ori);
  75391. }
  75392. }
  75393. else {
  75394. result = ori === "true" ? true : false;
  75395. }
  75396. }
  75397. }
  75398. // the whole parenthesis scope is replaced by 'true' or 'false'
  75399. return result ? "true" : "false";
  75400. };
  75401. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75402. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75403. // remove whitespaces
  75404. r = r.replace(/[\s]/g, function () { return ""; });
  75405. return r.length % 2 ? "!" : "";
  75406. });
  75407. booleanString = booleanString.trim();
  75408. if (booleanString === "!true") {
  75409. booleanString = "false";
  75410. }
  75411. else if (booleanString === "!false") {
  75412. booleanString = "true";
  75413. }
  75414. return booleanString;
  75415. };
  75416. return AndOrNotEvaluator;
  75417. }());
  75418. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75419. })(BABYLON || (BABYLON = {}));
  75420. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75421. var BABYLON;
  75422. (function (BABYLON) {
  75423. /**
  75424. * Class used to enable access to IndexedDB
  75425. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75426. */
  75427. var Database = /** @class */ (function () {
  75428. /**
  75429. * Creates a new Database
  75430. * @param urlToScene defines the url to load the scene
  75431. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75432. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75433. */
  75434. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75435. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75436. var _this = this;
  75437. // Handling various flavors of prefixed version of IndexedDB
  75438. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75439. this.callbackManifestChecked = callbackManifestChecked;
  75440. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75441. this.db = null;
  75442. this._enableSceneOffline = false;
  75443. this._enableTexturesOffline = false;
  75444. this.manifestVersionFound = 0;
  75445. this.mustUpdateRessources = false;
  75446. this.hasReachedQuota = false;
  75447. if (!Database.IDBStorageEnabled) {
  75448. this.callbackManifestChecked(true);
  75449. }
  75450. else {
  75451. if (disableManifestCheck) {
  75452. this._enableSceneOffline = true;
  75453. this._enableTexturesOffline = true;
  75454. this.manifestVersionFound = 1;
  75455. BABYLON.Tools.SetImmediate(function () {
  75456. _this.callbackManifestChecked(true);
  75457. });
  75458. }
  75459. else {
  75460. this._checkManifestFile();
  75461. }
  75462. }
  75463. }
  75464. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75465. /**
  75466. * Gets a boolean indicating if scene must be saved in the database
  75467. */
  75468. get: function () {
  75469. return this._enableSceneOffline;
  75470. },
  75471. enumerable: true,
  75472. configurable: true
  75473. });
  75474. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75475. /**
  75476. * Gets a boolean indicating if textures must be saved in the database
  75477. */
  75478. get: function () {
  75479. return this._enableTexturesOffline;
  75480. },
  75481. enumerable: true,
  75482. configurable: true
  75483. });
  75484. Database.prototype._checkManifestFile = function () {
  75485. var _this = this;
  75486. var noManifestFile = function () {
  75487. _this._enableSceneOffline = false;
  75488. _this._enableTexturesOffline = false;
  75489. _this.callbackManifestChecked(false);
  75490. };
  75491. var timeStampUsed = false;
  75492. var manifestURL = this.currentSceneUrl + ".manifest";
  75493. var xhr = new XMLHttpRequest();
  75494. if (navigator.onLine) {
  75495. // Adding a timestamp to by-pass browsers' cache
  75496. timeStampUsed = true;
  75497. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75498. }
  75499. xhr.open("GET", manifestURL, true);
  75500. xhr.addEventListener("load", function () {
  75501. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75502. try {
  75503. var manifestFile = JSON.parse(xhr.response);
  75504. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75505. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75506. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75507. _this.manifestVersionFound = manifestFile.version;
  75508. }
  75509. if (_this.callbackManifestChecked) {
  75510. _this.callbackManifestChecked(true);
  75511. }
  75512. }
  75513. catch (ex) {
  75514. noManifestFile();
  75515. }
  75516. }
  75517. else {
  75518. noManifestFile();
  75519. }
  75520. }, false);
  75521. xhr.addEventListener("error", function (event) {
  75522. if (timeStampUsed) {
  75523. timeStampUsed = false;
  75524. // Let's retry without the timeStamp
  75525. // It could fail when coupled with HTML5 Offline API
  75526. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75527. xhr.open("GET", retryManifestURL, true);
  75528. xhr.send();
  75529. }
  75530. else {
  75531. noManifestFile();
  75532. }
  75533. }, false);
  75534. try {
  75535. xhr.send();
  75536. }
  75537. catch (ex) {
  75538. BABYLON.Tools.Error("Error on XHR send request.");
  75539. this.callbackManifestChecked(false);
  75540. }
  75541. };
  75542. /**
  75543. * Open the database and make it available
  75544. * @param successCallback defines the callback to call on success
  75545. * @param errorCallback defines the callback to call on error
  75546. */
  75547. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75548. var _this = this;
  75549. var handleError = function () {
  75550. _this.isSupported = false;
  75551. if (errorCallback)
  75552. errorCallback();
  75553. };
  75554. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75555. // Your browser doesn't support IndexedDB
  75556. this.isSupported = false;
  75557. if (errorCallback)
  75558. errorCallback();
  75559. }
  75560. else {
  75561. // If the DB hasn't been opened or created yet
  75562. if (!this.db) {
  75563. this.hasReachedQuota = false;
  75564. this.isSupported = true;
  75565. var request = this.idbFactory.open("babylonjs", 1);
  75566. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75567. request.onerror = function (event) {
  75568. handleError();
  75569. };
  75570. // executes when a version change transaction cannot complete due to other active transactions
  75571. request.onblocked = function (event) {
  75572. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75573. handleError();
  75574. };
  75575. // DB has been opened successfully
  75576. request.onsuccess = function (event) {
  75577. _this.db = request.result;
  75578. successCallback();
  75579. };
  75580. // Initialization of the DB. Creating Scenes & Textures stores
  75581. request.onupgradeneeded = function (event) {
  75582. _this.db = (event.target).result;
  75583. if (_this.db) {
  75584. try {
  75585. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75586. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75587. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75588. }
  75589. catch (ex) {
  75590. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75591. handleError();
  75592. }
  75593. }
  75594. };
  75595. }
  75596. // DB has already been created and opened
  75597. else {
  75598. if (successCallback)
  75599. successCallback();
  75600. }
  75601. }
  75602. };
  75603. /**
  75604. * Loads an image from the database
  75605. * @param url defines the url to load from
  75606. * @param image defines the target DOM image
  75607. */
  75608. Database.prototype.loadImageFromDB = function (url, image) {
  75609. var _this = this;
  75610. var completeURL = Database._ReturnFullUrlLocation(url);
  75611. var saveAndLoadImage = function () {
  75612. if (!_this.hasReachedQuota && _this.db !== null) {
  75613. // the texture is not yet in the DB, let's try to save it
  75614. _this._saveImageIntoDBAsync(completeURL, image);
  75615. }
  75616. // If the texture is not in the DB and we've reached the DB quota limit
  75617. // let's load it directly from the web
  75618. else {
  75619. image.src = url;
  75620. }
  75621. };
  75622. if (!this.mustUpdateRessources) {
  75623. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75624. }
  75625. // First time we're download the images or update requested in the manifest file by a version change
  75626. else {
  75627. saveAndLoadImage();
  75628. }
  75629. };
  75630. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75631. if (this.isSupported && this.db !== null) {
  75632. var texture;
  75633. var transaction = this.db.transaction(["textures"]);
  75634. transaction.onabort = function (event) {
  75635. image.src = url;
  75636. };
  75637. transaction.oncomplete = function (event) {
  75638. var blobTextureURL;
  75639. if (texture) {
  75640. var URL = window.URL || window.webkitURL;
  75641. blobTextureURL = URL.createObjectURL(texture.data);
  75642. image.onerror = function () {
  75643. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75644. image.src = url;
  75645. };
  75646. image.src = blobTextureURL;
  75647. }
  75648. else {
  75649. notInDBCallback();
  75650. }
  75651. };
  75652. var getRequest = transaction.objectStore("textures").get(url);
  75653. getRequest.onsuccess = function (event) {
  75654. texture = (event.target).result;
  75655. };
  75656. getRequest.onerror = function (event) {
  75657. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75658. image.src = url;
  75659. };
  75660. }
  75661. else {
  75662. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75663. image.src = url;
  75664. }
  75665. };
  75666. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75667. var _this = this;
  75668. if (this.isSupported) {
  75669. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75670. var generateBlobUrl = function () {
  75671. var blobTextureURL;
  75672. if (blob) {
  75673. var URL = window.URL || window.webkitURL;
  75674. try {
  75675. blobTextureURL = URL.createObjectURL(blob);
  75676. }
  75677. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75678. catch (ex) {
  75679. blobTextureURL = URL.createObjectURL(blob);
  75680. }
  75681. }
  75682. if (blobTextureURL) {
  75683. image.src = blobTextureURL;
  75684. }
  75685. };
  75686. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75687. var xhr = new XMLHttpRequest(), blob;
  75688. xhr.open("GET", url, true);
  75689. xhr.responseType = "blob";
  75690. xhr.addEventListener("load", function () {
  75691. if (xhr.status === 200 && _this.db) {
  75692. // Blob as response (XHR2)
  75693. blob = xhr.response;
  75694. var transaction = _this.db.transaction(["textures"], "readwrite");
  75695. // the transaction could abort because of a QuotaExceededError error
  75696. transaction.onabort = function (event) {
  75697. try {
  75698. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75699. var srcElement = (event.srcElement || event.target);
  75700. var error = srcElement.error;
  75701. if (error && error.name === "QuotaExceededError") {
  75702. _this.hasReachedQuota = true;
  75703. }
  75704. }
  75705. catch (ex) { }
  75706. generateBlobUrl();
  75707. };
  75708. transaction.oncomplete = function (event) {
  75709. generateBlobUrl();
  75710. };
  75711. var newTexture = { textureUrl: url, data: blob };
  75712. try {
  75713. // Put the blob into the dabase
  75714. var addRequest = transaction.objectStore("textures").put(newTexture);
  75715. addRequest.onsuccess = function (event) {
  75716. };
  75717. addRequest.onerror = function (event) {
  75718. generateBlobUrl();
  75719. };
  75720. }
  75721. catch (ex) {
  75722. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75723. if (ex.code === 25) {
  75724. Database.IsUASupportingBlobStorage = false;
  75725. }
  75726. image.src = url;
  75727. }
  75728. }
  75729. else {
  75730. image.src = url;
  75731. }
  75732. }, false);
  75733. xhr.addEventListener("error", function (event) {
  75734. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75735. image.src = url;
  75736. }, false);
  75737. xhr.send();
  75738. }
  75739. else {
  75740. image.src = url;
  75741. }
  75742. }
  75743. else {
  75744. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75745. image.src = url;
  75746. }
  75747. };
  75748. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75749. var _this = this;
  75750. var updateVersion = function () {
  75751. // the version is not yet in the DB or we need to update it
  75752. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75753. };
  75754. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75755. };
  75756. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75757. var _this = this;
  75758. if (this.isSupported && this.db) {
  75759. var version;
  75760. try {
  75761. var transaction = this.db.transaction(["versions"]);
  75762. transaction.oncomplete = function (event) {
  75763. if (version) {
  75764. // If the version in the JSON file is different from the version in DB
  75765. if (_this.manifestVersionFound !== version.data) {
  75766. _this.mustUpdateRessources = true;
  75767. updateInDBCallback();
  75768. }
  75769. else {
  75770. callback(version.data);
  75771. }
  75772. }
  75773. // version was not found in DB
  75774. else {
  75775. _this.mustUpdateRessources = true;
  75776. updateInDBCallback();
  75777. }
  75778. };
  75779. transaction.onabort = function (event) {
  75780. callback(-1);
  75781. };
  75782. var getRequest = transaction.objectStore("versions").get(url);
  75783. getRequest.onsuccess = function (event) {
  75784. version = (event.target).result;
  75785. };
  75786. getRequest.onerror = function (event) {
  75787. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75788. callback(-1);
  75789. };
  75790. }
  75791. catch (ex) {
  75792. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75793. callback(-1);
  75794. }
  75795. }
  75796. else {
  75797. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75798. callback(-1);
  75799. }
  75800. };
  75801. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75802. var _this = this;
  75803. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75804. try {
  75805. // Open a transaction to the database
  75806. var transaction = this.db.transaction(["versions"], "readwrite");
  75807. // the transaction could abort because of a QuotaExceededError error
  75808. transaction.onabort = function (event) {
  75809. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75810. var error = event.srcElement['error'];
  75811. if (error && error.name === "QuotaExceededError") {
  75812. _this.hasReachedQuota = true;
  75813. }
  75814. }
  75815. catch (ex) { }
  75816. callback(-1);
  75817. };
  75818. transaction.oncomplete = function (event) {
  75819. callback(_this.manifestVersionFound);
  75820. };
  75821. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75822. // Put the scene into the database
  75823. var addRequest = transaction.objectStore("versions").put(newVersion);
  75824. addRequest.onsuccess = function (event) {
  75825. };
  75826. addRequest.onerror = function (event) {
  75827. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75828. };
  75829. }
  75830. catch (ex) {
  75831. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75832. callback(-1);
  75833. }
  75834. }
  75835. else {
  75836. callback(-1);
  75837. }
  75838. };
  75839. /**
  75840. * Loads a file from database
  75841. * @param url defines the URL to load from
  75842. * @param sceneLoaded defines a callback to call on success
  75843. * @param progressCallBack defines a callback to call when progress changed
  75844. * @param errorCallback defines a callback to call on error
  75845. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75846. */
  75847. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75848. var _this = this;
  75849. var completeUrl = Database._ReturnFullUrlLocation(url);
  75850. var saveAndLoadFile = function () {
  75851. // the scene is not yet in the DB, let's try to save it
  75852. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75853. };
  75854. this._checkVersionFromDB(completeUrl, function (version) {
  75855. if (version !== -1) {
  75856. if (!_this.mustUpdateRessources) {
  75857. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75858. }
  75859. else {
  75860. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75861. }
  75862. }
  75863. else {
  75864. if (errorCallback) {
  75865. errorCallback();
  75866. }
  75867. }
  75868. });
  75869. };
  75870. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75871. if (this.isSupported && this.db) {
  75872. var targetStore;
  75873. if (url.indexOf(".babylon") !== -1) {
  75874. targetStore = "scenes";
  75875. }
  75876. else {
  75877. targetStore = "textures";
  75878. }
  75879. var file;
  75880. var transaction = this.db.transaction([targetStore]);
  75881. transaction.oncomplete = function (event) {
  75882. if (file) {
  75883. callback(file.data);
  75884. }
  75885. // file was not found in DB
  75886. else {
  75887. notInDBCallback();
  75888. }
  75889. };
  75890. transaction.onabort = function (event) {
  75891. notInDBCallback();
  75892. };
  75893. var getRequest = transaction.objectStore(targetStore).get(url);
  75894. getRequest.onsuccess = function (event) {
  75895. file = (event.target).result;
  75896. };
  75897. getRequest.onerror = function (event) {
  75898. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75899. notInDBCallback();
  75900. };
  75901. }
  75902. else {
  75903. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75904. callback();
  75905. }
  75906. };
  75907. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75908. var _this = this;
  75909. if (this.isSupported) {
  75910. var targetStore;
  75911. if (url.indexOf(".babylon") !== -1) {
  75912. targetStore = "scenes";
  75913. }
  75914. else {
  75915. targetStore = "textures";
  75916. }
  75917. // Create XHR
  75918. var xhr = new XMLHttpRequest();
  75919. var fileData;
  75920. xhr.open("GET", url + "?" + Date.now(), true);
  75921. if (useArrayBuffer) {
  75922. xhr.responseType = "arraybuffer";
  75923. }
  75924. if (progressCallback) {
  75925. xhr.onprogress = progressCallback;
  75926. }
  75927. xhr.addEventListener("load", function () {
  75928. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75929. // Blob as response (XHR2)
  75930. //fileData = xhr.responseText;
  75931. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75932. if (!_this.hasReachedQuota && _this.db) {
  75933. // Open a transaction to the database
  75934. var transaction = _this.db.transaction([targetStore], "readwrite");
  75935. // the transaction could abort because of a QuotaExceededError error
  75936. transaction.onabort = function (event) {
  75937. try {
  75938. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75939. var error = event.srcElement['error'];
  75940. if (error && error.name === "QuotaExceededError") {
  75941. _this.hasReachedQuota = true;
  75942. }
  75943. }
  75944. catch (ex) { }
  75945. callback(fileData);
  75946. };
  75947. transaction.oncomplete = function (event) {
  75948. callback(fileData);
  75949. };
  75950. var newFile;
  75951. if (targetStore === "scenes") {
  75952. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75953. }
  75954. else {
  75955. newFile = { textureUrl: url, data: fileData };
  75956. }
  75957. try {
  75958. // Put the scene into the database
  75959. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75960. addRequest.onsuccess = function (event) {
  75961. };
  75962. addRequest.onerror = function (event) {
  75963. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75964. };
  75965. }
  75966. catch (ex) {
  75967. callback(fileData);
  75968. }
  75969. }
  75970. else {
  75971. callback(fileData);
  75972. }
  75973. }
  75974. else {
  75975. if (xhr.status >= 400 && errorCallback) {
  75976. errorCallback(xhr);
  75977. }
  75978. else {
  75979. callback();
  75980. }
  75981. }
  75982. }, false);
  75983. xhr.addEventListener("error", function (event) {
  75984. BABYLON.Tools.Error("error on XHR request.");
  75985. callback();
  75986. }, false);
  75987. xhr.send();
  75988. }
  75989. else {
  75990. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75991. callback();
  75992. }
  75993. };
  75994. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  75995. Database.IsUASupportingBlobStorage = true;
  75996. /** Gets a boolean indicating if Database storate is enabled */
  75997. Database.IDBStorageEnabled = true;
  75998. Database._ParseURL = function (url) {
  75999. var a = document.createElement('a');
  76000. a.href = url;
  76001. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  76002. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  76003. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  76004. return absLocation;
  76005. };
  76006. Database._ReturnFullUrlLocation = function (url) {
  76007. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  76008. return (Database._ParseURL(window.location.href) + url);
  76009. }
  76010. else {
  76011. return url;
  76012. }
  76013. };
  76014. return Database;
  76015. }());
  76016. BABYLON.Database = Database;
  76017. })(BABYLON || (BABYLON = {}));
  76018. //# sourceMappingURL=babylon.database.js.map
  76019. var BABYLON;
  76020. (function (BABYLON) {
  76021. var FresnelParameters = /** @class */ (function () {
  76022. function FresnelParameters() {
  76023. this._isEnabled = true;
  76024. this.leftColor = BABYLON.Color3.White();
  76025. this.rightColor = BABYLON.Color3.Black();
  76026. this.bias = 0;
  76027. this.power = 1;
  76028. }
  76029. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  76030. get: function () {
  76031. return this._isEnabled;
  76032. },
  76033. set: function (value) {
  76034. if (this._isEnabled === value) {
  76035. return;
  76036. }
  76037. this._isEnabled = value;
  76038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  76039. },
  76040. enumerable: true,
  76041. configurable: true
  76042. });
  76043. FresnelParameters.prototype.clone = function () {
  76044. var newFresnelParameters = new FresnelParameters();
  76045. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  76046. return newFresnelParameters;
  76047. };
  76048. FresnelParameters.prototype.serialize = function () {
  76049. var serializationObject = {};
  76050. serializationObject.isEnabled = this.isEnabled;
  76051. serializationObject.leftColor = this.leftColor.asArray();
  76052. serializationObject.rightColor = this.rightColor.asArray();
  76053. serializationObject.bias = this.bias;
  76054. serializationObject.power = this.power;
  76055. return serializationObject;
  76056. };
  76057. FresnelParameters.Parse = function (parsedFresnelParameters) {
  76058. var fresnelParameters = new FresnelParameters();
  76059. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  76060. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  76061. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  76062. fresnelParameters.bias = parsedFresnelParameters.bias;
  76063. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  76064. return fresnelParameters;
  76065. };
  76066. return FresnelParameters;
  76067. }());
  76068. BABYLON.FresnelParameters = FresnelParameters;
  76069. })(BABYLON || (BABYLON = {}));
  76070. //# sourceMappingURL=babylon.fresnelParameters.js.map
  76071. var BABYLON;
  76072. (function (BABYLON) {
  76073. var MultiMaterial = /** @class */ (function (_super) {
  76074. __extends(MultiMaterial, _super);
  76075. function MultiMaterial(name, scene) {
  76076. var _this = _super.call(this, name, scene, true) || this;
  76077. scene.multiMaterials.push(_this);
  76078. _this.subMaterials = new Array();
  76079. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  76080. return _this;
  76081. }
  76082. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  76083. get: function () {
  76084. return this._subMaterials;
  76085. },
  76086. set: function (value) {
  76087. this._subMaterials = value;
  76088. this._hookArray(value);
  76089. },
  76090. enumerable: true,
  76091. configurable: true
  76092. });
  76093. MultiMaterial.prototype._hookArray = function (array) {
  76094. var _this = this;
  76095. var oldPush = array.push;
  76096. array.push = function () {
  76097. var items = [];
  76098. for (var _i = 0; _i < arguments.length; _i++) {
  76099. items[_i] = arguments[_i];
  76100. }
  76101. var result = oldPush.apply(array, items);
  76102. _this._markAllSubMeshesAsTexturesDirty();
  76103. return result;
  76104. };
  76105. var oldSplice = array.splice;
  76106. array.splice = function (index, deleteCount) {
  76107. var deleted = oldSplice.apply(array, [index, deleteCount]);
  76108. _this._markAllSubMeshesAsTexturesDirty();
  76109. return deleted;
  76110. };
  76111. };
  76112. // Properties
  76113. MultiMaterial.prototype.getSubMaterial = function (index) {
  76114. if (index < 0 || index >= this.subMaterials.length) {
  76115. return this.getScene().defaultMaterial;
  76116. }
  76117. return this.subMaterials[index];
  76118. };
  76119. MultiMaterial.prototype.getActiveTextures = function () {
  76120. var _a;
  76121. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  76122. if (subMaterial) {
  76123. return subMaterial.getActiveTextures();
  76124. }
  76125. else {
  76126. return [];
  76127. }
  76128. }));
  76129. };
  76130. // Methods
  76131. MultiMaterial.prototype.getClassName = function () {
  76132. return "MultiMaterial";
  76133. };
  76134. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76135. for (var index = 0; index < this.subMaterials.length; index++) {
  76136. var subMaterial = this.subMaterials[index];
  76137. if (subMaterial) {
  76138. if (subMaterial.storeEffectOnSubMeshes) {
  76139. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  76140. return false;
  76141. }
  76142. continue;
  76143. }
  76144. if (!subMaterial.isReady(mesh)) {
  76145. return false;
  76146. }
  76147. }
  76148. }
  76149. return true;
  76150. };
  76151. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  76152. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  76153. for (var index = 0; index < this.subMaterials.length; index++) {
  76154. var subMaterial = null;
  76155. var current = this.subMaterials[index];
  76156. if (cloneChildren && current) {
  76157. subMaterial = current.clone(name + "-" + current.name);
  76158. }
  76159. else {
  76160. subMaterial = this.subMaterials[index];
  76161. }
  76162. newMultiMaterial.subMaterials.push(subMaterial);
  76163. }
  76164. return newMultiMaterial;
  76165. };
  76166. MultiMaterial.prototype.serialize = function () {
  76167. var serializationObject = {};
  76168. serializationObject.name = this.name;
  76169. serializationObject.id = this.id;
  76170. if (BABYLON.Tags) {
  76171. serializationObject.tags = BABYLON.Tags.GetTags(this);
  76172. }
  76173. serializationObject.materials = [];
  76174. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  76175. var subMat = this.subMaterials[matIndex];
  76176. if (subMat) {
  76177. serializationObject.materials.push(subMat.id);
  76178. }
  76179. else {
  76180. serializationObject.materials.push(null);
  76181. }
  76182. }
  76183. return serializationObject;
  76184. };
  76185. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76186. var scene = this.getScene();
  76187. if (!scene) {
  76188. return;
  76189. }
  76190. var index = scene.multiMaterials.indexOf(this);
  76191. if (index >= 0) {
  76192. scene.multiMaterials.splice(index, 1);
  76193. }
  76194. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  76195. };
  76196. return MultiMaterial;
  76197. }(BABYLON.Material));
  76198. BABYLON.MultiMaterial = MultiMaterial;
  76199. })(BABYLON || (BABYLON = {}));
  76200. //# sourceMappingURL=babylon.multiMaterial.js.map
  76201. var BABYLON;
  76202. (function (BABYLON) {
  76203. /**
  76204. * Manage the touch inputs to control the movement of a free camera.
  76205. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76206. */
  76207. var FreeCameraTouchInput = /** @class */ (function () {
  76208. function FreeCameraTouchInput() {
  76209. /**
  76210. * Defines the touch sensibility for rotation.
  76211. * The higher the faster.
  76212. */
  76213. this.touchAngularSensibility = 200000.0;
  76214. /**
  76215. * Defines the touch sensibility for move.
  76216. * The higher the faster.
  76217. */
  76218. this.touchMoveSensibility = 250.0;
  76219. this._offsetX = null;
  76220. this._offsetY = null;
  76221. this._pointerPressed = new Array();
  76222. }
  76223. /**
  76224. * Attach the input controls to a specific dom element to get the input from.
  76225. * @param element Defines the element the controls should be listened from
  76226. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76227. */
  76228. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  76229. var _this = this;
  76230. var previousPosition = null;
  76231. if (this._pointerInput === undefined) {
  76232. this._onLostFocus = function (evt) {
  76233. _this._offsetX = null;
  76234. _this._offsetY = null;
  76235. };
  76236. this._pointerInput = function (p, s) {
  76237. var evt = p.event;
  76238. if (evt.pointerType === "mouse") {
  76239. return;
  76240. }
  76241. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76242. if (!noPreventDefault) {
  76243. evt.preventDefault();
  76244. }
  76245. _this._pointerPressed.push(evt.pointerId);
  76246. if (_this._pointerPressed.length !== 1) {
  76247. return;
  76248. }
  76249. previousPosition = {
  76250. x: evt.clientX,
  76251. y: evt.clientY
  76252. };
  76253. }
  76254. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  76255. if (!noPreventDefault) {
  76256. evt.preventDefault();
  76257. }
  76258. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76259. if (index === -1) {
  76260. return;
  76261. }
  76262. _this._pointerPressed.splice(index, 1);
  76263. if (index != 0) {
  76264. return;
  76265. }
  76266. previousPosition = null;
  76267. _this._offsetX = null;
  76268. _this._offsetY = null;
  76269. }
  76270. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  76271. if (!noPreventDefault) {
  76272. evt.preventDefault();
  76273. }
  76274. if (!previousPosition) {
  76275. return;
  76276. }
  76277. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76278. if (index != 0) {
  76279. return;
  76280. }
  76281. _this._offsetX = evt.clientX - previousPosition.x;
  76282. _this._offsetY = -(evt.clientY - previousPosition.y);
  76283. }
  76284. };
  76285. }
  76286. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  76287. if (this._onLostFocus) {
  76288. element.addEventListener("blur", this._onLostFocus);
  76289. }
  76290. };
  76291. /**
  76292. * Detach the current controls from the specified dom element.
  76293. * @param element Defines the element to stop listening the inputs from
  76294. */
  76295. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76296. if (this._pointerInput && element) {
  76297. if (this._observer) {
  76298. this.camera.getScene().onPointerObservable.remove(this._observer);
  76299. this._observer = null;
  76300. }
  76301. if (this._onLostFocus) {
  76302. element.removeEventListener("blur", this._onLostFocus);
  76303. this._onLostFocus = null;
  76304. }
  76305. this._pointerPressed = [];
  76306. this._offsetX = null;
  76307. this._offsetY = null;
  76308. }
  76309. };
  76310. /**
  76311. * Update the current camera state depending on the inputs that have been used this frame.
  76312. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76313. */
  76314. FreeCameraTouchInput.prototype.checkInputs = function () {
  76315. if (this._offsetX && this._offsetY) {
  76316. var camera = this.camera;
  76317. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76318. if (this._pointerPressed.length > 1) {
  76319. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76320. }
  76321. else {
  76322. var speed = camera._computeLocalCameraSpeed();
  76323. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76324. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76325. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76326. }
  76327. }
  76328. };
  76329. /**
  76330. * Gets the class name of the current intput.
  76331. * @returns the class name
  76332. */
  76333. FreeCameraTouchInput.prototype.getClassName = function () {
  76334. return "FreeCameraTouchInput";
  76335. };
  76336. /**
  76337. * Get the friendly name associated with the input class.
  76338. * @returns the input friendly name
  76339. */
  76340. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76341. return "touch";
  76342. };
  76343. __decorate([
  76344. BABYLON.serialize()
  76345. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76346. __decorate([
  76347. BABYLON.serialize()
  76348. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76349. return FreeCameraTouchInput;
  76350. }());
  76351. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76352. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76353. })(BABYLON || (BABYLON = {}));
  76354. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76355. var BABYLON;
  76356. (function (BABYLON) {
  76357. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76358. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76359. });
  76360. /**
  76361. * This represents a FPS type of camera controlled by touch.
  76362. * This is like a universal camera minus the Gamepad controls.
  76363. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76364. */
  76365. var TouchCamera = /** @class */ (function (_super) {
  76366. __extends(TouchCamera, _super);
  76367. /**
  76368. * Instantiates a new touch camera.
  76369. * This represents a FPS type of camera controlled by touch.
  76370. * This is like a universal camera minus the Gamepad controls.
  76371. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76372. * @param name Define the name of the camera in the scene
  76373. * @param position Define the start position of the camera in the scene
  76374. * @param scene Define the scene the camera belongs to
  76375. */
  76376. function TouchCamera(name, position, scene) {
  76377. var _this = _super.call(this, name, position, scene) || this;
  76378. _this.inputs.addTouch();
  76379. _this._setupInputs();
  76380. return _this;
  76381. }
  76382. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76383. /**
  76384. * Defines the touch sensibility for rotation.
  76385. * The higher the faster.
  76386. */
  76387. get: function () {
  76388. var touch = this.inputs.attached["touch"];
  76389. if (touch)
  76390. return touch.touchAngularSensibility;
  76391. return 0;
  76392. },
  76393. set: function (value) {
  76394. var touch = this.inputs.attached["touch"];
  76395. if (touch)
  76396. touch.touchAngularSensibility = value;
  76397. },
  76398. enumerable: true,
  76399. configurable: true
  76400. });
  76401. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76402. /**
  76403. * Defines the touch sensibility for move.
  76404. * The higher the faster.
  76405. */
  76406. get: function () {
  76407. var touch = this.inputs.attached["touch"];
  76408. if (touch)
  76409. return touch.touchMoveSensibility;
  76410. return 0;
  76411. },
  76412. set: function (value) {
  76413. var touch = this.inputs.attached["touch"];
  76414. if (touch)
  76415. touch.touchMoveSensibility = value;
  76416. },
  76417. enumerable: true,
  76418. configurable: true
  76419. });
  76420. /**
  76421. * Gets the current object class name.
  76422. * @return the class name
  76423. */
  76424. TouchCamera.prototype.getClassName = function () {
  76425. return "TouchCamera";
  76426. };
  76427. /** @hidden */
  76428. TouchCamera.prototype._setupInputs = function () {
  76429. var mouse = this.inputs.attached["mouse"];
  76430. if (mouse) {
  76431. mouse.touchEnabled = false;
  76432. }
  76433. };
  76434. return TouchCamera;
  76435. }(BABYLON.FreeCamera));
  76436. BABYLON.TouchCamera = TouchCamera;
  76437. })(BABYLON || (BABYLON = {}));
  76438. //# sourceMappingURL=babylon.touchCamera.js.map
  76439. var BABYLON;
  76440. (function (BABYLON) {
  76441. var ProceduralTexture = /** @class */ (function (_super) {
  76442. __extends(ProceduralTexture, _super);
  76443. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76444. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76445. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76446. if (isCube === void 0) { isCube = false; }
  76447. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76448. _this.isCube = isCube;
  76449. _this.isEnabled = true;
  76450. _this._currentRefreshId = -1;
  76451. _this._refreshRate = 1;
  76452. /**
  76453. * Event raised when the texture is generated
  76454. */
  76455. _this.onGeneratedObservable = new BABYLON.Observable();
  76456. _this._vertexBuffers = {};
  76457. _this._uniforms = new Array();
  76458. _this._samplers = new Array();
  76459. /** @hidden */
  76460. _this._textures = {};
  76461. _this._floats = {};
  76462. _this._ints = {};
  76463. _this._floatsArrays = {};
  76464. _this._colors3 = {};
  76465. _this._colors4 = {};
  76466. _this._vectors2 = {};
  76467. _this._vectors3 = {};
  76468. _this._matrices = {};
  76469. _this._fallbackTextureUsed = false;
  76470. _this._cachedDefines = "";
  76471. _this._contentUpdateId = -1;
  76472. scene = _this.getScene();
  76473. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76474. if (!component) {
  76475. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76476. scene._addComponent(component);
  76477. }
  76478. scene.proceduralTextures.push(_this);
  76479. _this._engine = scene.getEngine();
  76480. _this.name = name;
  76481. _this.isRenderTarget = true;
  76482. _this._size = size;
  76483. _this._generateMipMaps = generateMipMaps;
  76484. _this.setFragment(fragment);
  76485. _this._fallbackTexture = fallbackTexture;
  76486. if (isCube) {
  76487. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76488. _this.setFloat("face", 0);
  76489. }
  76490. else {
  76491. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76492. }
  76493. // VBO
  76494. var vertices = [];
  76495. vertices.push(1, 1);
  76496. vertices.push(-1, 1);
  76497. vertices.push(-1, -1);
  76498. vertices.push(1, -1);
  76499. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76500. _this._createIndexBuffer();
  76501. return _this;
  76502. }
  76503. /**
  76504. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76505. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76506. */
  76507. ProceduralTexture.prototype.getContent = function () {
  76508. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76509. return this._contentData;
  76510. }
  76511. this._contentData = this.readPixels(0, 0, this._contentData);
  76512. this._contentUpdateId = this._currentRefreshId;
  76513. return this._contentData;
  76514. };
  76515. ProceduralTexture.prototype._createIndexBuffer = function () {
  76516. var engine = this._engine;
  76517. // Indices
  76518. var indices = [];
  76519. indices.push(0);
  76520. indices.push(1);
  76521. indices.push(2);
  76522. indices.push(0);
  76523. indices.push(2);
  76524. indices.push(3);
  76525. this._indexBuffer = engine.createIndexBuffer(indices);
  76526. };
  76527. /** @hidden */
  76528. ProceduralTexture.prototype._rebuild = function () {
  76529. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76530. if (vb) {
  76531. vb._rebuild();
  76532. }
  76533. this._createIndexBuffer();
  76534. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76535. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76536. }
  76537. };
  76538. ProceduralTexture.prototype.reset = function () {
  76539. if (this._effect === undefined) {
  76540. return;
  76541. }
  76542. var engine = this._engine;
  76543. engine._releaseEffect(this._effect);
  76544. };
  76545. ProceduralTexture.prototype._getDefines = function () {
  76546. return "";
  76547. };
  76548. ProceduralTexture.prototype.isReady = function () {
  76549. var _this = this;
  76550. var engine = this._engine;
  76551. var shaders;
  76552. if (!this._fragment) {
  76553. return false;
  76554. }
  76555. if (this._fallbackTextureUsed) {
  76556. return true;
  76557. }
  76558. var defines = this._getDefines();
  76559. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76560. return true;
  76561. }
  76562. if (this._fragment.fragmentElement !== undefined) {
  76563. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76564. }
  76565. else {
  76566. shaders = { vertex: "procedural", fragment: this._fragment };
  76567. }
  76568. this._cachedDefines = defines;
  76569. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76570. _this.releaseInternalTexture();
  76571. if (_this._fallbackTexture) {
  76572. _this._texture = _this._fallbackTexture._texture;
  76573. if (_this._texture) {
  76574. _this._texture.incrementReferences();
  76575. }
  76576. }
  76577. _this._fallbackTextureUsed = true;
  76578. });
  76579. return this._effect.isReady();
  76580. };
  76581. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76582. this._currentRefreshId = -1;
  76583. };
  76584. ProceduralTexture.prototype.setFragment = function (fragment) {
  76585. this._fragment = fragment;
  76586. };
  76587. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76588. get: function () {
  76589. return this._refreshRate;
  76590. },
  76591. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76592. set: function (value) {
  76593. this._refreshRate = value;
  76594. this.resetRefreshCounter();
  76595. },
  76596. enumerable: true,
  76597. configurable: true
  76598. });
  76599. /** @hidden */
  76600. ProceduralTexture.prototype._shouldRender = function () {
  76601. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76602. if (this._texture) {
  76603. this._texture.isReady = false;
  76604. }
  76605. return false;
  76606. }
  76607. if (this._fallbackTextureUsed) {
  76608. return false;
  76609. }
  76610. if (this._currentRefreshId === -1) { // At least render once
  76611. this._currentRefreshId = 1;
  76612. return true;
  76613. }
  76614. if (this.refreshRate === this._currentRefreshId) {
  76615. this._currentRefreshId = 1;
  76616. return true;
  76617. }
  76618. this._currentRefreshId++;
  76619. return false;
  76620. };
  76621. ProceduralTexture.prototype.getRenderSize = function () {
  76622. return this._size;
  76623. };
  76624. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76625. if (this._fallbackTextureUsed) {
  76626. return;
  76627. }
  76628. this.releaseInternalTexture();
  76629. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76630. // Update properties
  76631. this._size = size;
  76632. this._generateMipMaps = generateMipMaps;
  76633. };
  76634. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76635. if (this._uniforms.indexOf(uniformName) === -1) {
  76636. this._uniforms.push(uniformName);
  76637. }
  76638. };
  76639. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76640. if (this._samplers.indexOf(name) === -1) {
  76641. this._samplers.push(name);
  76642. }
  76643. this._textures[name] = texture;
  76644. return this;
  76645. };
  76646. ProceduralTexture.prototype.setFloat = function (name, value) {
  76647. this._checkUniform(name);
  76648. this._floats[name] = value;
  76649. return this;
  76650. };
  76651. /**
  76652. * Set the value of an uniform to an integer value
  76653. * @param name defines the name of the uniform
  76654. * @param value defines the value to set
  76655. * @returns the current procedural texture
  76656. */
  76657. ProceduralTexture.prototype.setInt = function (name, value) {
  76658. this._checkUniform(name);
  76659. this._ints[name] = value;
  76660. return this;
  76661. };
  76662. ProceduralTexture.prototype.setFloats = function (name, value) {
  76663. this._checkUniform(name);
  76664. this._floatsArrays[name] = value;
  76665. return this;
  76666. };
  76667. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76668. this._checkUniform(name);
  76669. this._colors3[name] = value;
  76670. return this;
  76671. };
  76672. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76673. this._checkUniform(name);
  76674. this._colors4[name] = value;
  76675. return this;
  76676. };
  76677. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76678. this._checkUniform(name);
  76679. this._vectors2[name] = value;
  76680. return this;
  76681. };
  76682. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76683. this._checkUniform(name);
  76684. this._vectors3[name] = value;
  76685. return this;
  76686. };
  76687. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76688. this._checkUniform(name);
  76689. this._matrices[name] = value;
  76690. return this;
  76691. };
  76692. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76693. var scene = this.getScene();
  76694. if (!scene) {
  76695. return;
  76696. }
  76697. var engine = this._engine;
  76698. // Render
  76699. engine.enableEffect(this._effect);
  76700. engine.setState(false);
  76701. // Texture
  76702. for (var name in this._textures) {
  76703. this._effect.setTexture(name, this._textures[name]);
  76704. }
  76705. // Float
  76706. for (name in this._ints) {
  76707. this._effect.setInt(name, this._ints[name]);
  76708. }
  76709. // Float
  76710. for (name in this._floats) {
  76711. this._effect.setFloat(name, this._floats[name]);
  76712. }
  76713. // Floats
  76714. for (name in this._floatsArrays) {
  76715. this._effect.setArray(name, this._floatsArrays[name]);
  76716. }
  76717. // Color3
  76718. for (name in this._colors3) {
  76719. this._effect.setColor3(name, this._colors3[name]);
  76720. }
  76721. // Color4
  76722. for (name in this._colors4) {
  76723. var color = this._colors4[name];
  76724. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76725. }
  76726. // Vector2
  76727. for (name in this._vectors2) {
  76728. this._effect.setVector2(name, this._vectors2[name]);
  76729. }
  76730. // Vector3
  76731. for (name in this._vectors3) {
  76732. this._effect.setVector3(name, this._vectors3[name]);
  76733. }
  76734. // Matrix
  76735. for (name in this._matrices) {
  76736. this._effect.setMatrix(name, this._matrices[name]);
  76737. }
  76738. if (!this._texture) {
  76739. return;
  76740. }
  76741. if (this.isCube) {
  76742. for (var face = 0; face < 6; face++) {
  76743. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76744. // VBOs
  76745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76746. this._effect.setFloat("face", face);
  76747. // Clear
  76748. engine.clear(scene.clearColor, true, true, true);
  76749. // Draw order
  76750. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76751. // Mipmaps
  76752. if (face === 5) {
  76753. engine.generateMipMapsForCubemap(this._texture);
  76754. }
  76755. }
  76756. }
  76757. else {
  76758. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76759. // VBOs
  76760. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76761. // Clear
  76762. engine.clear(scene.clearColor, true, true, true);
  76763. // Draw order
  76764. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76765. }
  76766. // Unbind
  76767. engine.unBindFramebuffer(this._texture, this.isCube);
  76768. if (this.onGenerated) {
  76769. this.onGenerated();
  76770. }
  76771. this.onGeneratedObservable.notifyObservers(this);
  76772. };
  76773. ProceduralTexture.prototype.clone = function () {
  76774. var textureSize = this.getSize();
  76775. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76776. // Base texture
  76777. newTexture.hasAlpha = this.hasAlpha;
  76778. newTexture.level = this.level;
  76779. // RenderTarget Texture
  76780. newTexture.coordinatesMode = this.coordinatesMode;
  76781. return newTexture;
  76782. };
  76783. ProceduralTexture.prototype.dispose = function () {
  76784. var scene = this.getScene();
  76785. if (!scene) {
  76786. return;
  76787. }
  76788. var index = scene.proceduralTextures.indexOf(this);
  76789. if (index >= 0) {
  76790. scene.proceduralTextures.splice(index, 1);
  76791. }
  76792. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76793. if (vertexBuffer) {
  76794. vertexBuffer.dispose();
  76795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76796. }
  76797. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76798. this._indexBuffer = null;
  76799. }
  76800. _super.prototype.dispose.call(this);
  76801. };
  76802. __decorate([
  76803. BABYLON.serialize()
  76804. ], ProceduralTexture.prototype, "_size", void 0);
  76805. __decorate([
  76806. BABYLON.serialize()
  76807. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76808. __decorate([
  76809. BABYLON.serialize()
  76810. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76811. __decorate([
  76812. BABYLON.serialize()
  76813. ], ProceduralTexture.prototype, "refreshRate", null);
  76814. return ProceduralTexture;
  76815. }(BABYLON.Texture));
  76816. BABYLON.ProceduralTexture = ProceduralTexture;
  76817. })(BABYLON || (BABYLON = {}));
  76818. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76819. var BABYLON;
  76820. (function (BABYLON) {
  76821. /**
  76822. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76823. * in a given scene.
  76824. */
  76825. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76826. /**
  76827. * Creates a new instance of the component for the given scene
  76828. * @param scene Defines the scene to register the component in
  76829. */
  76830. function ProceduralTextureSceneComponent(scene) {
  76831. /**
  76832. * The component name helpfull to identify the component in the list of scene components.
  76833. */
  76834. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76835. this.scene = scene;
  76836. this.scene.proceduralTextures = new Array();
  76837. scene.layers = new Array();
  76838. }
  76839. /**
  76840. * Registers the component in a given scene
  76841. */
  76842. ProceduralTextureSceneComponent.prototype.register = function () {
  76843. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76844. };
  76845. /**
  76846. * Rebuilds the elements related to this component in case of
  76847. * context lost for instance.
  76848. */
  76849. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76850. // Nothing to do here.
  76851. };
  76852. /**
  76853. * Disposes the component and the associated ressources.
  76854. */
  76855. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76856. // Nothing to do here.
  76857. };
  76858. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76859. if (this.scene.proceduralTexturesEnabled) {
  76860. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76861. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76862. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76863. if (proceduralTexture._shouldRender()) {
  76864. proceduralTexture.render();
  76865. }
  76866. }
  76867. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76868. }
  76869. };
  76870. return ProceduralTextureSceneComponent;
  76871. }());
  76872. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76873. })(BABYLON || (BABYLON = {}));
  76874. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76875. var BABYLON;
  76876. (function (BABYLON) {
  76877. var CustomProceduralTexture = /** @class */ (function (_super) {
  76878. __extends(CustomProceduralTexture, _super);
  76879. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76880. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76881. _this._animate = true;
  76882. _this._time = 0;
  76883. _this._texturePath = texturePath;
  76884. //Try to load json
  76885. _this.loadJson(texturePath);
  76886. _this.refreshRate = 1;
  76887. return _this;
  76888. }
  76889. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76890. var _this = this;
  76891. var noConfigFile = function () {
  76892. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76893. try {
  76894. _this.setFragment(_this._texturePath);
  76895. }
  76896. catch (ex) {
  76897. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76898. }
  76899. };
  76900. var configFileUrl = jsonUrl + "/config.json";
  76901. var xhr = new XMLHttpRequest();
  76902. xhr.open("GET", configFileUrl, true);
  76903. xhr.addEventListener("load", function () {
  76904. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76905. try {
  76906. _this._config = JSON.parse(xhr.response);
  76907. _this.updateShaderUniforms();
  76908. _this.updateTextures();
  76909. _this.setFragment(_this._texturePath + "/custom");
  76910. _this._animate = _this._config.animate;
  76911. _this.refreshRate = _this._config.refreshrate;
  76912. }
  76913. catch (ex) {
  76914. noConfigFile();
  76915. }
  76916. }
  76917. else {
  76918. noConfigFile();
  76919. }
  76920. }, false);
  76921. xhr.addEventListener("error", function () {
  76922. noConfigFile();
  76923. }, false);
  76924. try {
  76925. xhr.send();
  76926. }
  76927. catch (ex) {
  76928. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76929. }
  76930. };
  76931. CustomProceduralTexture.prototype.isReady = function () {
  76932. if (!_super.prototype.isReady.call(this)) {
  76933. return false;
  76934. }
  76935. for (var name in this._textures) {
  76936. var texture = this._textures[name];
  76937. if (!texture.isReady()) {
  76938. return false;
  76939. }
  76940. }
  76941. return true;
  76942. };
  76943. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76944. var scene = this.getScene();
  76945. if (this._animate && scene) {
  76946. this._time += scene.getAnimationRatio() * 0.03;
  76947. this.updateShaderUniforms();
  76948. }
  76949. _super.prototype.render.call(this, useCameraPostProcess);
  76950. };
  76951. CustomProceduralTexture.prototype.updateTextures = function () {
  76952. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76953. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76954. }
  76955. };
  76956. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76957. if (this._config) {
  76958. for (var j = 0; j < this._config.uniforms.length; j++) {
  76959. var uniform = this._config.uniforms[j];
  76960. switch (uniform.type) {
  76961. case "float":
  76962. this.setFloat(uniform.name, uniform.value);
  76963. break;
  76964. case "color3":
  76965. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76966. break;
  76967. case "color4":
  76968. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76969. break;
  76970. case "vector2":
  76971. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76972. break;
  76973. case "vector3":
  76974. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  76975. break;
  76976. }
  76977. }
  76978. }
  76979. this.setFloat("time", this._time);
  76980. };
  76981. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  76982. get: function () {
  76983. return this._animate;
  76984. },
  76985. set: function (value) {
  76986. this._animate = value;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. return CustomProceduralTexture;
  76992. }(BABYLON.ProceduralTexture));
  76993. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  76994. })(BABYLON || (BABYLON = {}));
  76995. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  76996. var BABYLON;
  76997. (function (BABYLON) {
  76998. /**
  76999. * Manage the gamepad inputs to control a free camera.
  77000. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77001. */
  77002. var FreeCameraGamepadInput = /** @class */ (function () {
  77003. function FreeCameraGamepadInput() {
  77004. /**
  77005. * Defines the gamepad rotation sensiblity.
  77006. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77007. */
  77008. this.gamepadAngularSensibility = 200;
  77009. /**
  77010. * Defines the gamepad move sensiblity.
  77011. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77012. */
  77013. this.gamepadMoveSensibility = 40;
  77014. this._cameraTransform = BABYLON.Matrix.Identity();
  77015. this._deltaTransform = BABYLON.Vector3.Zero();
  77016. this._vector3 = BABYLON.Vector3.Zero();
  77017. this._vector2 = BABYLON.Vector2.Zero();
  77018. }
  77019. /**
  77020. * Attach the input controls to a specific dom element to get the input from.
  77021. * @param element Defines the element the controls should be listened from
  77022. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77023. */
  77024. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77025. var _this = this;
  77026. var manager = this.camera.getScene().gamepadManager;
  77027. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77028. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77029. // prioritize XBOX gamepads.
  77030. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77031. _this.gamepad = gamepad;
  77032. }
  77033. }
  77034. });
  77035. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77036. if (_this.gamepad === gamepad) {
  77037. _this.gamepad = null;
  77038. }
  77039. });
  77040. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77041. };
  77042. /**
  77043. * Detach the current controls from the specified dom element.
  77044. * @param element Defines the element to stop listening the inputs from
  77045. */
  77046. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  77047. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77048. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77049. this.gamepad = null;
  77050. };
  77051. /**
  77052. * Update the current camera state depending on the inputs that have been used this frame.
  77053. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77054. */
  77055. FreeCameraGamepadInput.prototype.checkInputs = function () {
  77056. if (this.gamepad && this.gamepad.leftStick) {
  77057. var camera = this.camera;
  77058. var LSValues = this.gamepad.leftStick;
  77059. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  77060. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77061. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  77062. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  77063. var RSValues = this.gamepad.rightStick;
  77064. if (RSValues) {
  77065. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  77066. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  77067. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  77068. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  77069. }
  77070. else {
  77071. RSValues = { x: 0, y: 0 };
  77072. }
  77073. if (!camera.rotationQuaternion) {
  77074. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  77075. }
  77076. else {
  77077. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  77078. }
  77079. var speed = camera._computeLocalCameraSpeed() * 50.0;
  77080. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  77081. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  77082. camera.cameraDirection.addInPlace(this._deltaTransform);
  77083. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  77084. camera.cameraRotation.addInPlace(this._vector2);
  77085. }
  77086. };
  77087. /**
  77088. * Gets the class name of the current intput.
  77089. * @returns the class name
  77090. */
  77091. FreeCameraGamepadInput.prototype.getClassName = function () {
  77092. return "FreeCameraGamepadInput";
  77093. };
  77094. /**
  77095. * Get the friendly name associated with the input class.
  77096. * @returns the input friendly name
  77097. */
  77098. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  77099. return "gamepad";
  77100. };
  77101. __decorate([
  77102. BABYLON.serialize()
  77103. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  77104. __decorate([
  77105. BABYLON.serialize()
  77106. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77107. return FreeCameraGamepadInput;
  77108. }());
  77109. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  77110. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  77111. })(BABYLON || (BABYLON = {}));
  77112. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  77113. var BABYLON;
  77114. (function (BABYLON) {
  77115. /**
  77116. * Manage the gamepad inputs to control an arc rotate camera.
  77117. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77118. */
  77119. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  77120. function ArcRotateCameraGamepadInput() {
  77121. /**
  77122. * Defines the gamepad rotation sensiblity.
  77123. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77124. */
  77125. this.gamepadRotationSensibility = 80;
  77126. /**
  77127. * Defines the gamepad move sensiblity.
  77128. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77129. */
  77130. this.gamepadMoveSensibility = 40;
  77131. }
  77132. /**
  77133. * Attach the input controls to a specific dom element to get the input from.
  77134. * @param element Defines the element the controls should be listened from
  77135. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77136. */
  77137. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77138. var _this = this;
  77139. var manager = this.camera.getScene().gamepadManager;
  77140. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77141. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77142. // prioritize XBOX gamepads.
  77143. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77144. _this.gamepad = gamepad;
  77145. }
  77146. }
  77147. });
  77148. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77149. if (_this.gamepad === gamepad) {
  77150. _this.gamepad = null;
  77151. }
  77152. });
  77153. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77154. };
  77155. /**
  77156. * Detach the current controls from the specified dom element.
  77157. * @param element Defines the element to stop listening the inputs from
  77158. */
  77159. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  77160. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77161. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77162. this.gamepad = null;
  77163. };
  77164. /**
  77165. * Update the current camera state depending on the inputs that have been used this frame.
  77166. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77167. */
  77168. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  77169. if (this.gamepad) {
  77170. var camera = this.camera;
  77171. var RSValues = this.gamepad.rightStick;
  77172. if (RSValues) {
  77173. if (RSValues.x != 0) {
  77174. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  77175. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  77176. camera.inertialAlphaOffset += normalizedRX;
  77177. }
  77178. }
  77179. if (RSValues.y != 0) {
  77180. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  77181. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  77182. camera.inertialBetaOffset += normalizedRY;
  77183. }
  77184. }
  77185. }
  77186. var LSValues = this.gamepad.leftStick;
  77187. if (LSValues && LSValues.y != 0) {
  77188. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77189. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  77190. this.camera.inertialRadiusOffset -= normalizedLY;
  77191. }
  77192. }
  77193. }
  77194. };
  77195. /**
  77196. * Gets the class name of the current intput.
  77197. * @returns the class name
  77198. */
  77199. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  77200. return "ArcRotateCameraGamepadInput";
  77201. };
  77202. /**
  77203. * Get the friendly name associated with the input class.
  77204. * @returns the input friendly name
  77205. */
  77206. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  77207. return "gamepad";
  77208. };
  77209. __decorate([
  77210. BABYLON.serialize()
  77211. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  77212. __decorate([
  77213. BABYLON.serialize()
  77214. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77215. return ArcRotateCameraGamepadInput;
  77216. }());
  77217. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  77218. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  77219. })(BABYLON || (BABYLON = {}));
  77220. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  77221. var BABYLON;
  77222. (function (BABYLON) {
  77223. /**
  77224. * Manager for handling gamepads
  77225. */
  77226. var GamepadManager = /** @class */ (function () {
  77227. /**
  77228. * Initializes the gamepad manager
  77229. * @param _scene BabylonJS scene
  77230. */
  77231. function GamepadManager(_scene) {
  77232. var _this = this;
  77233. this._scene = _scene;
  77234. this._babylonGamepads = [];
  77235. this._oneGamepadConnected = false;
  77236. /** @hidden */
  77237. this._isMonitoring = false;
  77238. /**
  77239. * observable to be triggered when the gamepad controller has been disconnected
  77240. */
  77241. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  77242. if (!BABYLON.Tools.IsWindowObjectExist()) {
  77243. this._gamepadEventSupported = false;
  77244. }
  77245. else {
  77246. this._gamepadEventSupported = 'GamepadEvent' in window;
  77247. this._gamepadSupport = (navigator.getGamepads ||
  77248. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  77249. }
  77250. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  77251. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  77252. for (var i in _this._babylonGamepads) {
  77253. var gamepad = _this._babylonGamepads[i];
  77254. if (gamepad && gamepad._isConnected) {
  77255. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  77256. }
  77257. }
  77258. });
  77259. this._onGamepadConnectedEvent = function (evt) {
  77260. var gamepad = evt.gamepad;
  77261. if (gamepad.index in _this._babylonGamepads) {
  77262. if (_this._babylonGamepads[gamepad.index].isConnected) {
  77263. return;
  77264. }
  77265. }
  77266. var newGamepad;
  77267. if (_this._babylonGamepads[gamepad.index]) {
  77268. newGamepad = _this._babylonGamepads[gamepad.index];
  77269. newGamepad.browserGamepad = gamepad;
  77270. newGamepad._isConnected = true;
  77271. }
  77272. else {
  77273. newGamepad = _this._addNewGamepad(gamepad);
  77274. }
  77275. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77276. _this._startMonitoringGamepads();
  77277. };
  77278. this._onGamepadDisconnectedEvent = function (evt) {
  77279. var gamepad = evt.gamepad;
  77280. // Remove the gamepad from the list of gamepads to monitor.
  77281. for (var i in _this._babylonGamepads) {
  77282. if (_this._babylonGamepads[i].index === gamepad.index) {
  77283. var disconnectedGamepad = _this._babylonGamepads[i];
  77284. disconnectedGamepad._isConnected = false;
  77285. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  77286. break;
  77287. }
  77288. }
  77289. };
  77290. if (this._gamepadSupport) {
  77291. //first add already-connected gamepads
  77292. this._updateGamepadObjects();
  77293. if (this._babylonGamepads.length) {
  77294. this._startMonitoringGamepads();
  77295. }
  77296. // Checking if the gamepad connected event is supported (like in Firefox)
  77297. if (this._gamepadEventSupported) {
  77298. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77299. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77300. }
  77301. else {
  77302. this._startMonitoringGamepads();
  77303. }
  77304. }
  77305. }
  77306. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77307. /**
  77308. * The gamepads in the game pad manager
  77309. */
  77310. get: function () {
  77311. return this._babylonGamepads;
  77312. },
  77313. enumerable: true,
  77314. configurable: true
  77315. });
  77316. /**
  77317. * Get the gamepad controllers based on type
  77318. * @param type The type of gamepad controller
  77319. * @returns Nullable gamepad
  77320. */
  77321. GamepadManager.prototype.getGamepadByType = function (type) {
  77322. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77323. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77324. var gamepad = _a[_i];
  77325. if (gamepad && gamepad.type === type) {
  77326. return gamepad;
  77327. }
  77328. }
  77329. return null;
  77330. };
  77331. /**
  77332. * Disposes the gamepad manager
  77333. */
  77334. GamepadManager.prototype.dispose = function () {
  77335. if (this._gamepadEventSupported) {
  77336. if (this._onGamepadConnectedEvent) {
  77337. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77338. }
  77339. if (this._onGamepadDisconnectedEvent) {
  77340. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77341. }
  77342. this._onGamepadConnectedEvent = null;
  77343. this._onGamepadDisconnectedEvent = null;
  77344. }
  77345. this._babylonGamepads.forEach(function (gamepad) {
  77346. gamepad.dispose();
  77347. });
  77348. this.onGamepadConnectedObservable.clear();
  77349. this.onGamepadDisconnectedObservable.clear();
  77350. this._oneGamepadConnected = false;
  77351. this._stopMonitoringGamepads();
  77352. this._babylonGamepads = [];
  77353. };
  77354. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77355. if (!this._oneGamepadConnected) {
  77356. this._oneGamepadConnected = true;
  77357. }
  77358. var newGamepad;
  77359. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77360. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77361. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77362. }
  77363. // if pose is supported, use the (WebVR) pose enabled controller
  77364. else if (gamepad.pose) {
  77365. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77366. }
  77367. else {
  77368. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77369. }
  77370. this._babylonGamepads[newGamepad.index] = newGamepad;
  77371. return newGamepad;
  77372. };
  77373. GamepadManager.prototype._startMonitoringGamepads = function () {
  77374. if (!this._isMonitoring) {
  77375. this._isMonitoring = true;
  77376. //back-comp
  77377. if (!this._scene) {
  77378. this._checkGamepadsStatus();
  77379. }
  77380. }
  77381. };
  77382. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77383. this._isMonitoring = false;
  77384. };
  77385. /** @hidden */
  77386. GamepadManager.prototype._checkGamepadsStatus = function () {
  77387. var _this = this;
  77388. // Hack to be compatible Chrome
  77389. this._updateGamepadObjects();
  77390. for (var i in this._babylonGamepads) {
  77391. var gamepad = this._babylonGamepads[i];
  77392. if (!gamepad || !gamepad.isConnected) {
  77393. continue;
  77394. }
  77395. gamepad.update();
  77396. }
  77397. if (this._isMonitoring && !this._scene) {
  77398. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77399. }
  77400. };
  77401. // This function is called only on Chrome, which does not properly support
  77402. // connection/disconnection events and forces you to recopy again the gamepad object
  77403. GamepadManager.prototype._updateGamepadObjects = function () {
  77404. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77405. for (var i = 0; i < gamepads.length; i++) {
  77406. var gamepad = gamepads[i];
  77407. if (gamepad) {
  77408. if (!this._babylonGamepads[gamepad.index]) {
  77409. var newGamepad = this._addNewGamepad(gamepad);
  77410. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77411. }
  77412. else {
  77413. // Forced to copy again this object for Chrome for unknown reason
  77414. this._babylonGamepads[i].browserGamepad = gamepad;
  77415. if (!this._babylonGamepads[i].isConnected) {
  77416. this._babylonGamepads[i]._isConnected = true;
  77417. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77418. }
  77419. }
  77420. }
  77421. }
  77422. };
  77423. return GamepadManager;
  77424. }());
  77425. BABYLON.GamepadManager = GamepadManager;
  77426. })(BABYLON || (BABYLON = {}));
  77427. //# sourceMappingURL=babylon.gamepadManager.js.map
  77428. var BABYLON;
  77429. (function (BABYLON) {
  77430. /**
  77431. * Represents a gamepad control stick position
  77432. */
  77433. var StickValues = /** @class */ (function () {
  77434. /**
  77435. * Initializes the gamepad x and y control stick values
  77436. * @param x The x component of the gamepad control stick value
  77437. * @param y The y component of the gamepad control stick value
  77438. */
  77439. function StickValues(
  77440. /**
  77441. * The x component of the control stick
  77442. */
  77443. x,
  77444. /**
  77445. * The y component of the control stick
  77446. */
  77447. y) {
  77448. this.x = x;
  77449. this.y = y;
  77450. }
  77451. return StickValues;
  77452. }());
  77453. BABYLON.StickValues = StickValues;
  77454. /**
  77455. * Represents a gamepad
  77456. */
  77457. var Gamepad = /** @class */ (function () {
  77458. /**
  77459. * Initializes the gamepad
  77460. * @param id The id of the gamepad
  77461. * @param index The index of the gamepad
  77462. * @param browserGamepad The browser gamepad
  77463. * @param leftStickX The x component of the left joystick
  77464. * @param leftStickY The y component of the left joystick
  77465. * @param rightStickX The x component of the right joystick
  77466. * @param rightStickY The y component of the right joystick
  77467. */
  77468. function Gamepad(
  77469. /**
  77470. * The id of the gamepad
  77471. */
  77472. id,
  77473. /**
  77474. * The index of the gamepad
  77475. */
  77476. index,
  77477. /**
  77478. * The browser gamepad
  77479. */
  77480. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77481. if (leftStickX === void 0) { leftStickX = 0; }
  77482. if (leftStickY === void 0) { leftStickY = 1; }
  77483. if (rightStickX === void 0) { rightStickX = 2; }
  77484. if (rightStickY === void 0) { rightStickY = 3; }
  77485. this.id = id;
  77486. this.index = index;
  77487. this.browserGamepad = browserGamepad;
  77488. this._leftStick = { x: 0, y: 0 };
  77489. this._rightStick = { x: 0, y: 0 };
  77490. /** @hidden */
  77491. this._isConnected = true;
  77492. /**
  77493. * Specifies whether the left control stick should be Y-inverted
  77494. */
  77495. this._invertLeftStickY = false;
  77496. this.type = Gamepad.GAMEPAD;
  77497. this._leftStickAxisX = leftStickX;
  77498. this._leftStickAxisY = leftStickY;
  77499. this._rightStickAxisX = rightStickX;
  77500. this._rightStickAxisY = rightStickY;
  77501. if (this.browserGamepad.axes.length >= 2) {
  77502. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77503. }
  77504. if (this.browserGamepad.axes.length >= 4) {
  77505. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77506. }
  77507. }
  77508. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77509. /**
  77510. * Specifies if the gamepad has been connected
  77511. */
  77512. get: function () {
  77513. return this._isConnected;
  77514. },
  77515. enumerable: true,
  77516. configurable: true
  77517. });
  77518. /**
  77519. * Callback triggered when the left joystick has changed
  77520. * @param callback
  77521. */
  77522. Gamepad.prototype.onleftstickchanged = function (callback) {
  77523. this._onleftstickchanged = callback;
  77524. };
  77525. /**
  77526. * Callback triggered when the right joystick has changed
  77527. * @param callback
  77528. */
  77529. Gamepad.prototype.onrightstickchanged = function (callback) {
  77530. this._onrightstickchanged = callback;
  77531. };
  77532. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77533. /**
  77534. * Gets the left joystick
  77535. */
  77536. get: function () {
  77537. return this._leftStick;
  77538. },
  77539. /**
  77540. * Sets the left joystick values
  77541. */
  77542. set: function (newValues) {
  77543. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77544. this._onleftstickchanged(newValues);
  77545. }
  77546. this._leftStick = newValues;
  77547. },
  77548. enumerable: true,
  77549. configurable: true
  77550. });
  77551. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77552. /**
  77553. * Gets the right joystick
  77554. */
  77555. get: function () {
  77556. return this._rightStick;
  77557. },
  77558. /**
  77559. * Sets the right joystick value
  77560. */
  77561. set: function (newValues) {
  77562. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77563. this._onrightstickchanged(newValues);
  77564. }
  77565. this._rightStick = newValues;
  77566. },
  77567. enumerable: true,
  77568. configurable: true
  77569. });
  77570. /**
  77571. * Updates the gamepad joystick positions
  77572. */
  77573. Gamepad.prototype.update = function () {
  77574. if (this._leftStick) {
  77575. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77576. if (this._invertLeftStickY) {
  77577. this.leftStick.y *= -1;
  77578. }
  77579. }
  77580. if (this._rightStick) {
  77581. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77582. }
  77583. };
  77584. /**
  77585. * Disposes the gamepad
  77586. */
  77587. Gamepad.prototype.dispose = function () {
  77588. };
  77589. /**
  77590. * Represents a gamepad controller
  77591. */
  77592. Gamepad.GAMEPAD = 0;
  77593. /**
  77594. * Represents a generic controller
  77595. */
  77596. Gamepad.GENERIC = 1;
  77597. /**
  77598. * Represents an XBox controller
  77599. */
  77600. Gamepad.XBOX = 2;
  77601. /**
  77602. * Represents a pose-enabled controller
  77603. */
  77604. Gamepad.POSE_ENABLED = 3;
  77605. return Gamepad;
  77606. }());
  77607. BABYLON.Gamepad = Gamepad;
  77608. /**
  77609. * Represents a generic gamepad
  77610. */
  77611. var GenericPad = /** @class */ (function (_super) {
  77612. __extends(GenericPad, _super);
  77613. /**
  77614. * Initializes the generic gamepad
  77615. * @param id The id of the generic gamepad
  77616. * @param index The index of the generic gamepad
  77617. * @param browserGamepad The browser gamepad
  77618. */
  77619. function GenericPad(id, index, browserGamepad) {
  77620. var _this = _super.call(this, id, index, browserGamepad) || this;
  77621. /**
  77622. * Observable triggered when a button has been pressed
  77623. */
  77624. _this.onButtonDownObservable = new BABYLON.Observable();
  77625. /**
  77626. * Observable triggered when a button has been released
  77627. */
  77628. _this.onButtonUpObservable = new BABYLON.Observable();
  77629. _this.type = Gamepad.GENERIC;
  77630. _this._buttons = new Array(browserGamepad.buttons.length);
  77631. return _this;
  77632. }
  77633. /**
  77634. * Callback triggered when a button has been pressed
  77635. * @param callback Called when a button has been pressed
  77636. */
  77637. GenericPad.prototype.onbuttondown = function (callback) {
  77638. this._onbuttondown = callback;
  77639. };
  77640. /**
  77641. * Callback triggered when a button has been released
  77642. * @param callback Called when a button has been released
  77643. */
  77644. GenericPad.prototype.onbuttonup = function (callback) {
  77645. this._onbuttonup = callback;
  77646. };
  77647. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77648. if (newValue !== currentValue) {
  77649. if (newValue === 1) {
  77650. if (this._onbuttondown) {
  77651. this._onbuttondown(buttonIndex);
  77652. }
  77653. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77654. }
  77655. if (newValue === 0) {
  77656. if (this._onbuttonup) {
  77657. this._onbuttonup(buttonIndex);
  77658. }
  77659. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77660. }
  77661. }
  77662. return newValue;
  77663. };
  77664. /**
  77665. * Updates the generic gamepad
  77666. */
  77667. GenericPad.prototype.update = function () {
  77668. _super.prototype.update.call(this);
  77669. for (var index = 0; index < this._buttons.length; index++) {
  77670. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  77671. }
  77672. };
  77673. /**
  77674. * Disposes the generic gamepad
  77675. */
  77676. GenericPad.prototype.dispose = function () {
  77677. _super.prototype.dispose.call(this);
  77678. this.onButtonDownObservable.clear();
  77679. this.onButtonUpObservable.clear();
  77680. };
  77681. return GenericPad;
  77682. }(Gamepad));
  77683. BABYLON.GenericPad = GenericPad;
  77684. })(BABYLON || (BABYLON = {}));
  77685. //# sourceMappingURL=babylon.gamepad.js.map
  77686. var BABYLON;
  77687. (function (BABYLON) {
  77688. /**
  77689. * Defines supported buttons for XBox360 compatible gamepads
  77690. */
  77691. var Xbox360Button;
  77692. (function (Xbox360Button) {
  77693. /** A */
  77694. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  77695. /** B */
  77696. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  77697. /** X */
  77698. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  77699. /** Y */
  77700. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  77701. /** Start */
  77702. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  77703. /** Back */
  77704. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  77705. /** Left button */
  77706. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  77707. /** Right button */
  77708. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  77709. /** Left stick */
  77710. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  77711. /** Right stick */
  77712. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  77713. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  77714. /** Defines values for XBox360 DPad */
  77715. var Xbox360Dpad;
  77716. (function (Xbox360Dpad) {
  77717. /** Up */
  77718. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  77719. /** Down */
  77720. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  77721. /** Left */
  77722. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  77723. /** Right */
  77724. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  77725. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  77726. /**
  77727. * Defines a XBox360 gamepad
  77728. */
  77729. var Xbox360Pad = /** @class */ (function (_super) {
  77730. __extends(Xbox360Pad, _super);
  77731. /**
  77732. * Creates a new XBox360 gamepad object
  77733. * @param id defines the id of this gamepad
  77734. * @param index defines its index
  77735. * @param gamepad defines the internal HTML gamepad object
  77736. * @param xboxOne defines if it is a XBox One gamepad
  77737. */
  77738. function Xbox360Pad(id, index, gamepad, xboxOne) {
  77739. if (xboxOne === void 0) { xboxOne = false; }
  77740. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  77741. _this._leftTrigger = 0;
  77742. _this._rightTrigger = 0;
  77743. /** Observable raised when a button is pressed */
  77744. _this.onButtonDownObservable = new BABYLON.Observable();
  77745. /** Observable raised when a button is released */
  77746. _this.onButtonUpObservable = new BABYLON.Observable();
  77747. /** Observable raised when a pad is pressed */
  77748. _this.onPadDownObservable = new BABYLON.Observable();
  77749. /** Observable raised when a pad is released */
  77750. _this.onPadUpObservable = new BABYLON.Observable();
  77751. _this._buttonA = 0;
  77752. _this._buttonB = 0;
  77753. _this._buttonX = 0;
  77754. _this._buttonY = 0;
  77755. _this._buttonBack = 0;
  77756. _this._buttonStart = 0;
  77757. _this._buttonLB = 0;
  77758. _this._buttonRB = 0;
  77759. _this._buttonLeftStick = 0;
  77760. _this._buttonRightStick = 0;
  77761. _this._dPadUp = 0;
  77762. _this._dPadDown = 0;
  77763. _this._dPadLeft = 0;
  77764. _this._dPadRight = 0;
  77765. _this._isXboxOnePad = false;
  77766. _this.type = BABYLON.Gamepad.XBOX;
  77767. _this._isXboxOnePad = xboxOne;
  77768. return _this;
  77769. }
  77770. /**
  77771. * Defines the callback to call when left trigger is pressed
  77772. * @param callback defines the callback to use
  77773. */
  77774. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  77775. this._onlefttriggerchanged = callback;
  77776. };
  77777. /**
  77778. * Defines the callback to call when right trigger is pressed
  77779. * @param callback defines the callback to use
  77780. */
  77781. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  77782. this._onrighttriggerchanged = callback;
  77783. };
  77784. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77785. /**
  77786. * Gets the left trigger value
  77787. */
  77788. get: function () {
  77789. return this._leftTrigger;
  77790. },
  77791. /**
  77792. * Sets the left trigger value
  77793. */
  77794. set: function (newValue) {
  77795. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77796. this._onlefttriggerchanged(newValue);
  77797. }
  77798. this._leftTrigger = newValue;
  77799. },
  77800. enumerable: true,
  77801. configurable: true
  77802. });
  77803. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77804. /**
  77805. * Gets the right trigger value
  77806. */
  77807. get: function () {
  77808. return this._rightTrigger;
  77809. },
  77810. /**
  77811. * Sets the right trigger value
  77812. */
  77813. set: function (newValue) {
  77814. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77815. this._onrighttriggerchanged(newValue);
  77816. }
  77817. this._rightTrigger = newValue;
  77818. },
  77819. enumerable: true,
  77820. configurable: true
  77821. });
  77822. /**
  77823. * Defines the callback to call when a button is pressed
  77824. * @param callback defines the callback to use
  77825. */
  77826. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77827. this._onbuttondown = callback;
  77828. };
  77829. /**
  77830. * Defines the callback to call when a button is released
  77831. * @param callback defines the callback to use
  77832. */
  77833. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77834. this._onbuttonup = callback;
  77835. };
  77836. /**
  77837. * Defines the callback to call when a pad is pressed
  77838. * @param callback defines the callback to use
  77839. */
  77840. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77841. this._ondpaddown = callback;
  77842. };
  77843. /**
  77844. * Defines the callback to call when a pad is released
  77845. * @param callback defines the callback to use
  77846. */
  77847. Xbox360Pad.prototype.ondpadup = function (callback) {
  77848. this._ondpadup = callback;
  77849. };
  77850. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77851. if (newValue !== currentValue) {
  77852. if (newValue === 1) {
  77853. if (this._onbuttondown) {
  77854. this._onbuttondown(buttonType);
  77855. }
  77856. this.onButtonDownObservable.notifyObservers(buttonType);
  77857. }
  77858. if (newValue === 0) {
  77859. if (this._onbuttonup) {
  77860. this._onbuttonup(buttonType);
  77861. }
  77862. this.onButtonUpObservable.notifyObservers(buttonType);
  77863. }
  77864. }
  77865. return newValue;
  77866. };
  77867. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77868. if (newValue !== currentValue) {
  77869. if (newValue === 1) {
  77870. if (this._ondpaddown) {
  77871. this._ondpaddown(buttonType);
  77872. }
  77873. this.onPadDownObservable.notifyObservers(buttonType);
  77874. }
  77875. if (newValue === 0) {
  77876. if (this._ondpadup) {
  77877. this._ondpadup(buttonType);
  77878. }
  77879. this.onPadUpObservable.notifyObservers(buttonType);
  77880. }
  77881. }
  77882. return newValue;
  77883. };
  77884. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77885. /**
  77886. * Gets the value of the `A` button
  77887. */
  77888. get: function () {
  77889. return this._buttonA;
  77890. },
  77891. /**
  77892. * Sets the value of the `A` button
  77893. */
  77894. set: function (value) {
  77895. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77896. },
  77897. enumerable: true,
  77898. configurable: true
  77899. });
  77900. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77901. /**
  77902. * Gets the value of the `B` button
  77903. */
  77904. get: function () {
  77905. return this._buttonB;
  77906. },
  77907. /**
  77908. * Sets the value of the `B` button
  77909. */
  77910. set: function (value) {
  77911. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77912. },
  77913. enumerable: true,
  77914. configurable: true
  77915. });
  77916. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77917. /**
  77918. * Gets the value of the `X` button
  77919. */
  77920. get: function () {
  77921. return this._buttonX;
  77922. },
  77923. /**
  77924. * Sets the value of the `X` button
  77925. */
  77926. set: function (value) {
  77927. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77928. },
  77929. enumerable: true,
  77930. configurable: true
  77931. });
  77932. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77933. /**
  77934. * Gets the value of the `Y` button
  77935. */
  77936. get: function () {
  77937. return this._buttonY;
  77938. },
  77939. /**
  77940. * Sets the value of the `Y` button
  77941. */
  77942. set: function (value) {
  77943. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77944. },
  77945. enumerable: true,
  77946. configurable: true
  77947. });
  77948. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77949. /**
  77950. * Gets the value of the `Start` button
  77951. */
  77952. get: function () {
  77953. return this._buttonStart;
  77954. },
  77955. /**
  77956. * Sets the value of the `Start` button
  77957. */
  77958. set: function (value) {
  77959. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77960. },
  77961. enumerable: true,
  77962. configurable: true
  77963. });
  77964. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77965. /**
  77966. * Gets the value of the `Back` button
  77967. */
  77968. get: function () {
  77969. return this._buttonBack;
  77970. },
  77971. /**
  77972. * Sets the value of the `Back` button
  77973. */
  77974. set: function (value) {
  77975. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  77976. },
  77977. enumerable: true,
  77978. configurable: true
  77979. });
  77980. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  77981. /**
  77982. * Gets the value of the `Left` button
  77983. */
  77984. get: function () {
  77985. return this._buttonLB;
  77986. },
  77987. /**
  77988. * Sets the value of the `Left` button
  77989. */
  77990. set: function (value) {
  77991. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  77992. },
  77993. enumerable: true,
  77994. configurable: true
  77995. });
  77996. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  77997. /**
  77998. * Gets the value of the `Right` button
  77999. */
  78000. get: function () {
  78001. return this._buttonRB;
  78002. },
  78003. /**
  78004. * Sets the value of the `Right` button
  78005. */
  78006. set: function (value) {
  78007. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  78008. },
  78009. enumerable: true,
  78010. configurable: true
  78011. });
  78012. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  78013. /**
  78014. * Gets the value of the Left joystick
  78015. */
  78016. get: function () {
  78017. return this._buttonLeftStick;
  78018. },
  78019. /**
  78020. * Sets the value of the Left joystick
  78021. */
  78022. set: function (value) {
  78023. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  78024. },
  78025. enumerable: true,
  78026. configurable: true
  78027. });
  78028. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  78029. /**
  78030. * Gets the value of the Right joystick
  78031. */
  78032. get: function () {
  78033. return this._buttonRightStick;
  78034. },
  78035. /**
  78036. * Sets the value of the Right joystick
  78037. */
  78038. set: function (value) {
  78039. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  78040. },
  78041. enumerable: true,
  78042. configurable: true
  78043. });
  78044. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  78045. /**
  78046. * Gets the value of D-pad up
  78047. */
  78048. get: function () {
  78049. return this._dPadUp;
  78050. },
  78051. /**
  78052. * Sets the value of D-pad up
  78053. */
  78054. set: function (value) {
  78055. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  78056. },
  78057. enumerable: true,
  78058. configurable: true
  78059. });
  78060. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  78061. /**
  78062. * Gets the value of D-pad down
  78063. */
  78064. get: function () {
  78065. return this._dPadDown;
  78066. },
  78067. /**
  78068. * Sets the value of D-pad down
  78069. */
  78070. set: function (value) {
  78071. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  78072. },
  78073. enumerable: true,
  78074. configurable: true
  78075. });
  78076. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  78077. /**
  78078. * Gets the value of D-pad left
  78079. */
  78080. get: function () {
  78081. return this._dPadLeft;
  78082. },
  78083. /**
  78084. * Sets the value of D-pad left
  78085. */
  78086. set: function (value) {
  78087. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  78088. },
  78089. enumerable: true,
  78090. configurable: true
  78091. });
  78092. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  78093. /**
  78094. * Gets the value of D-pad right
  78095. */
  78096. get: function () {
  78097. return this._dPadRight;
  78098. },
  78099. /**
  78100. * Sets the value of D-pad right
  78101. */
  78102. set: function (value) {
  78103. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  78104. },
  78105. enumerable: true,
  78106. configurable: true
  78107. });
  78108. /**
  78109. * Force the gamepad to synchronize with device values
  78110. */
  78111. Xbox360Pad.prototype.update = function () {
  78112. _super.prototype.update.call(this);
  78113. if (this._isXboxOnePad) {
  78114. this.buttonA = this.browserGamepad.buttons[0].value;
  78115. this.buttonB = this.browserGamepad.buttons[1].value;
  78116. this.buttonX = this.browserGamepad.buttons[2].value;
  78117. this.buttonY = this.browserGamepad.buttons[3].value;
  78118. this.buttonLB = this.browserGamepad.buttons[4].value;
  78119. this.buttonRB = this.browserGamepad.buttons[5].value;
  78120. this.leftTrigger = this.browserGamepad.axes[2];
  78121. this.rightTrigger = this.browserGamepad.axes[5];
  78122. this.buttonBack = this.browserGamepad.buttons[9].value;
  78123. this.buttonStart = this.browserGamepad.buttons[8].value;
  78124. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  78125. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  78126. this.dPadUp = this.browserGamepad.buttons[11].value;
  78127. this.dPadDown = this.browserGamepad.buttons[12].value;
  78128. this.dPadLeft = this.browserGamepad.buttons[13].value;
  78129. this.dPadRight = this.browserGamepad.buttons[14].value;
  78130. }
  78131. else {
  78132. this.buttonA = this.browserGamepad.buttons[0].value;
  78133. this.buttonB = this.browserGamepad.buttons[1].value;
  78134. this.buttonX = this.browserGamepad.buttons[2].value;
  78135. this.buttonY = this.browserGamepad.buttons[3].value;
  78136. this.buttonLB = this.browserGamepad.buttons[4].value;
  78137. this.buttonRB = this.browserGamepad.buttons[5].value;
  78138. this.leftTrigger = this.browserGamepad.buttons[6].value;
  78139. this.rightTrigger = this.browserGamepad.buttons[7].value;
  78140. this.buttonBack = this.browserGamepad.buttons[8].value;
  78141. this.buttonStart = this.browserGamepad.buttons[9].value;
  78142. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  78143. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  78144. this.dPadUp = this.browserGamepad.buttons[12].value;
  78145. this.dPadDown = this.browserGamepad.buttons[13].value;
  78146. this.dPadLeft = this.browserGamepad.buttons[14].value;
  78147. this.dPadRight = this.browserGamepad.buttons[15].value;
  78148. }
  78149. };
  78150. /**
  78151. * Disposes the gamepad
  78152. */
  78153. Xbox360Pad.prototype.dispose = function () {
  78154. _super.prototype.dispose.call(this);
  78155. this.onButtonDownObservable.clear();
  78156. this.onButtonUpObservable.clear();
  78157. this.onPadDownObservable.clear();
  78158. this.onPadUpObservable.clear();
  78159. };
  78160. return Xbox360Pad;
  78161. }(BABYLON.Gamepad));
  78162. BABYLON.Xbox360Pad = Xbox360Pad;
  78163. })(BABYLON || (BABYLON = {}));
  78164. //# sourceMappingURL=babylon.xboxGamepad.js.map
  78165. var BABYLON;
  78166. (function (BABYLON) {
  78167. /**
  78168. * Defines the types of pose enabled controllers that are supported
  78169. */
  78170. var PoseEnabledControllerType;
  78171. (function (PoseEnabledControllerType) {
  78172. /**
  78173. * HTC Vive
  78174. */
  78175. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  78176. /**
  78177. * Oculus Rift
  78178. */
  78179. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  78180. /**
  78181. * Windows mixed reality
  78182. */
  78183. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  78184. /**
  78185. * Samsung gear VR
  78186. */
  78187. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  78188. /**
  78189. * Google Daydream
  78190. */
  78191. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  78192. /**
  78193. * Generic
  78194. */
  78195. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  78196. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  78197. /**
  78198. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78199. */
  78200. var PoseEnabledControllerHelper = /** @class */ (function () {
  78201. function PoseEnabledControllerHelper() {
  78202. }
  78203. /**
  78204. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78205. * @param vrGamepad the gamepad to initialized
  78206. * @returns a vr controller of the type the gamepad identified as
  78207. */
  78208. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  78209. // Oculus Touch
  78210. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  78211. return new BABYLON.OculusTouchController(vrGamepad);
  78212. }
  78213. // Windows Mixed Reality controllers
  78214. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  78215. return new BABYLON.WindowsMotionController(vrGamepad);
  78216. }
  78217. // HTC Vive
  78218. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  78219. return new BABYLON.ViveController(vrGamepad);
  78220. }
  78221. // Samsung/Oculus Gear VR or Oculus Go
  78222. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  78223. return new BABYLON.GearVRController(vrGamepad);
  78224. }
  78225. // Google Daydream
  78226. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  78227. return new BABYLON.DaydreamController(vrGamepad);
  78228. }
  78229. // Generic
  78230. else {
  78231. return new BABYLON.GenericController(vrGamepad);
  78232. }
  78233. };
  78234. return PoseEnabledControllerHelper;
  78235. }());
  78236. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  78237. /**
  78238. * Defines the PoseEnabledController object that contains state of a vr capable controller
  78239. */
  78240. var PoseEnabledController = /** @class */ (function (_super) {
  78241. __extends(PoseEnabledController, _super);
  78242. /**
  78243. * Creates a new PoseEnabledController from a gamepad
  78244. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  78245. */
  78246. function PoseEnabledController(browserGamepad) {
  78247. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  78248. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78249. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78250. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  78251. /**
  78252. * The device position in babylon space
  78253. */
  78254. _this.devicePosition = BABYLON.Vector3.Zero();
  78255. /**
  78256. * The device rotation in babylon space
  78257. */
  78258. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  78259. /**
  78260. * The scale factor of the device in babylon space
  78261. */
  78262. _this.deviceScaleFactor = 1;
  78263. // Used to convert 6dof controllers to 3dof
  78264. _this._trackPosition = true;
  78265. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78266. _this._draggedRoomRotation = 0;
  78267. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  78268. /**
  78269. * Internal, matrix used to convert room space to babylon space
  78270. * @hidden
  78271. */
  78272. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78273. /**
  78274. * Node to be used when casting a ray from the controller
  78275. * @hidden
  78276. */
  78277. _this._pointingPoseNode = null;
  78278. _this._workingMatrix = BABYLON.Matrix.Identity();
  78279. /**
  78280. * @hidden
  78281. */
  78282. _this._meshAttachedObservable = new BABYLON.Observable();
  78283. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  78284. _this.controllerType = PoseEnabledControllerType.GENERIC;
  78285. _this.position = BABYLON.Vector3.Zero();
  78286. _this.rotationQuaternion = new BABYLON.Quaternion();
  78287. _this._calculatedPosition = BABYLON.Vector3.Zero();
  78288. _this._calculatedRotation = new BABYLON.Quaternion();
  78289. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  78290. return _this;
  78291. }
  78292. /**
  78293. * @hidden
  78294. */
  78295. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  78296. if (this._trackPosition) {
  78297. this._calculatedPosition.copyFrom(fixedPosition);
  78298. this._trackPosition = false;
  78299. }
  78300. };
  78301. /**
  78302. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  78303. */
  78304. PoseEnabledController.prototype.update = function () {
  78305. _super.prototype.update.call(this);
  78306. this._updatePoseAndMesh();
  78307. };
  78308. /**
  78309. * Updates only the pose device and mesh without doing any button event checking
  78310. */
  78311. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  78312. var pose = this.browserGamepad.pose;
  78313. this.updateFromDevice(pose);
  78314. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  78315. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78316. camera._computeDevicePosition();
  78317. this._deviceToWorld.setTranslation(camera.devicePosition);
  78318. if (camera.deviceRotationQuaternion) {
  78319. var camera = camera;
  78320. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  78321. // Find the radian distance away that the headset is from the controllers rotation
  78322. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  78323. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78324. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78325. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78326. this._draggedRoomRotation += rotationAmount;
  78327. // Rotate controller around headset
  78328. var sin = Math.sin(-rotationAmount);
  78329. var cos = Math.cos(-rotationAmount);
  78330. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78331. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78332. }
  78333. }
  78334. }
  78335. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  78336. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  78337. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78338. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  78339. if (this._mesh) {
  78340. this._mesh.position.copyFrom(this.devicePosition);
  78341. if (this._mesh.rotationQuaternion) {
  78342. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  78343. }
  78344. }
  78345. };
  78346. /**
  78347. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78348. * @param poseData raw pose fromthe device
  78349. */
  78350. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  78351. if (poseData) {
  78352. this.rawPose = poseData;
  78353. if (poseData.position) {
  78354. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  78355. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  78356. this._deviceRoomPosition.z *= -1;
  78357. }
  78358. if (this._trackPosition) {
  78359. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  78360. }
  78361. this._calculatedPosition.addInPlace(this.position);
  78362. }
  78363. var pose = this.rawPose;
  78364. if (poseData.orientation && pose.orientation) {
  78365. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  78366. if (this._mesh) {
  78367. if (this._mesh.getScene().useRightHandedSystem) {
  78368. this._deviceRoomRotationQuaternion.z *= -1;
  78369. this._deviceRoomRotationQuaternion.w *= -1;
  78370. }
  78371. else {
  78372. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  78373. }
  78374. }
  78375. // if the camera is set, rotate to the camera's rotation
  78376. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  78377. }
  78378. }
  78379. };
  78380. /**
  78381. * Attaches a mesh to the controller
  78382. * @param mesh the mesh to be attached
  78383. */
  78384. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  78385. if (this._mesh) {
  78386. this._mesh.parent = null;
  78387. }
  78388. this._mesh = mesh;
  78389. if (this._poseControlledCamera) {
  78390. this._mesh.parent = this._poseControlledCamera;
  78391. }
  78392. if (!this._mesh.rotationQuaternion) {
  78393. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  78394. }
  78395. // 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
  78396. this._updatePoseAndMesh();
  78397. if (this._pointingPoseNode) {
  78398. var parents = [];
  78399. var obj = this._pointingPoseNode;
  78400. while (obj.parent) {
  78401. parents.push(obj.parent);
  78402. obj = obj.parent;
  78403. }
  78404. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  78405. }
  78406. this._meshAttachedObservable.notifyObservers(mesh);
  78407. };
  78408. /**
  78409. * Attaches the controllers mesh to a camera
  78410. * @param camera the camera the mesh should be attached to
  78411. */
  78412. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  78413. this._poseControlledCamera = camera;
  78414. if (this._mesh) {
  78415. this._mesh.parent = this._poseControlledCamera;
  78416. }
  78417. };
  78418. /**
  78419. * Disposes of the controller
  78420. */
  78421. PoseEnabledController.prototype.dispose = function () {
  78422. if (this._mesh) {
  78423. this._mesh.dispose();
  78424. }
  78425. this._mesh = null;
  78426. _super.prototype.dispose.call(this);
  78427. };
  78428. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  78429. /**
  78430. * The mesh that is attached to the controller
  78431. */
  78432. get: function () {
  78433. return this._mesh;
  78434. },
  78435. enumerable: true,
  78436. configurable: true
  78437. });
  78438. /**
  78439. * Gets the ray of the controller in the direction the controller is pointing
  78440. * @param length the length the resulting ray should be
  78441. * @returns a ray in the direction the controller is pointing
  78442. */
  78443. PoseEnabledController.prototype.getForwardRay = function (length) {
  78444. if (length === void 0) { length = 100; }
  78445. if (!this.mesh) {
  78446. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  78447. }
  78448. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  78449. var origin = m.getTranslation();
  78450. var forward = new BABYLON.Vector3(0, 0, -1);
  78451. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78452. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78453. return new BABYLON.Ray(origin, direction, length);
  78454. };
  78455. /**
  78456. * Name of the child mesh that can be used to cast a ray from the controller
  78457. */
  78458. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  78459. return PoseEnabledController;
  78460. }(BABYLON.Gamepad));
  78461. BABYLON.PoseEnabledController = PoseEnabledController;
  78462. })(BABYLON || (BABYLON = {}));
  78463. //# sourceMappingURL=babylon.poseEnabledController.js.map
  78464. var BABYLON;
  78465. (function (BABYLON) {
  78466. /**
  78467. * Defines the WebVRController object that represents controllers tracked in 3D space
  78468. */
  78469. var WebVRController = /** @class */ (function (_super) {
  78470. __extends(WebVRController, _super);
  78471. /**
  78472. * Creates a new WebVRController from a gamepad
  78473. * @param vrGamepad the gamepad that the WebVRController should be created from
  78474. */
  78475. function WebVRController(vrGamepad) {
  78476. var _this = _super.call(this, vrGamepad) || this;
  78477. // Observables
  78478. /**
  78479. * Fired when the trigger state has changed
  78480. */
  78481. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  78482. /**
  78483. * Fired when the main button state has changed
  78484. */
  78485. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  78486. /**
  78487. * Fired when the secondary button state has changed
  78488. */
  78489. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  78490. /**
  78491. * Fired when the pad state has changed
  78492. */
  78493. _this.onPadStateChangedObservable = new BABYLON.Observable();
  78494. /**
  78495. * Fired when controllers stick values have changed
  78496. */
  78497. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  78498. /**
  78499. * X and Y axis corrisponding to the controllers joystick
  78500. */
  78501. _this.pad = { x: 0, y: 0 };
  78502. // avoid GC, store state in a tmp object
  78503. _this._changes = {
  78504. pressChanged: false,
  78505. touchChanged: false,
  78506. valueChanged: false,
  78507. changed: false
  78508. };
  78509. _this._buttons = new Array(vrGamepad.buttons.length);
  78510. _this.hand = vrGamepad.hand;
  78511. return _this;
  78512. }
  78513. /**
  78514. * Fired when a controller button's state has changed
  78515. * @param callback the callback containing the button that was modified
  78516. */
  78517. WebVRController.prototype.onButtonStateChange = function (callback) {
  78518. this._onButtonStateChange = callback;
  78519. };
  78520. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78521. /**
  78522. * The default controller model for the controller
  78523. */
  78524. get: function () {
  78525. return this._defaultModel;
  78526. },
  78527. enumerable: true,
  78528. configurable: true
  78529. });
  78530. /**
  78531. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78532. */
  78533. WebVRController.prototype.update = function () {
  78534. _super.prototype.update.call(this);
  78535. for (var index = 0; index < this._buttons.length; index++) {
  78536. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78537. }
  78538. ;
  78539. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78540. this.pad.x = this.leftStick.x;
  78541. this.pad.y = this.leftStick.y;
  78542. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78543. }
  78544. };
  78545. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78546. if (!newState) {
  78547. newState = {
  78548. pressed: false,
  78549. touched: false,
  78550. value: 0
  78551. };
  78552. }
  78553. if (!currentState) {
  78554. this._buttons[buttonIndex] = {
  78555. pressed: newState.pressed,
  78556. touched: newState.touched,
  78557. value: newState.value
  78558. };
  78559. return;
  78560. }
  78561. this._checkChanges(newState, currentState);
  78562. if (this._changes.changed) {
  78563. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78564. this._handleButtonChange(buttonIndex, newState, this._changes);
  78565. }
  78566. this._buttons[buttonIndex].pressed = newState.pressed;
  78567. this._buttons[buttonIndex].touched = newState.touched;
  78568. // oculus triggers are never 0, thou not touched.
  78569. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78570. };
  78571. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78572. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78573. this._changes.touchChanged = newState.touched !== currentState.touched;
  78574. this._changes.valueChanged = newState.value !== currentState.value;
  78575. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78576. return this._changes;
  78577. };
  78578. /**
  78579. * Disposes of th webVRCOntroller
  78580. */
  78581. WebVRController.prototype.dispose = function () {
  78582. _super.prototype.dispose.call(this);
  78583. this.onTriggerStateChangedObservable.clear();
  78584. this.onMainButtonStateChangedObservable.clear();
  78585. this.onSecondaryButtonStateChangedObservable.clear();
  78586. this.onPadStateChangedObservable.clear();
  78587. this.onPadValuesChangedObservable.clear();
  78588. };
  78589. return WebVRController;
  78590. }(BABYLON.PoseEnabledController));
  78591. BABYLON.WebVRController = WebVRController;
  78592. })(BABYLON || (BABYLON = {}));
  78593. //# sourceMappingURL=babylon.webVRController.js.map
  78594. var BABYLON;
  78595. (function (BABYLON) {
  78596. /**
  78597. * Oculus Touch Controller
  78598. */
  78599. var OculusTouchController = /** @class */ (function (_super) {
  78600. __extends(OculusTouchController, _super);
  78601. /**
  78602. * Creates a new OculusTouchController from a gamepad
  78603. * @param vrGamepad the gamepad that the controller should be created from
  78604. */
  78605. function OculusTouchController(vrGamepad) {
  78606. var _this = _super.call(this, vrGamepad) || this;
  78607. /**
  78608. * Fired when the secondary trigger on this controller is modified
  78609. */
  78610. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78611. /**
  78612. * Fired when the thumb rest on this controller is modified
  78613. */
  78614. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78615. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78616. return _this;
  78617. }
  78618. /**
  78619. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78620. * @param scene scene in which to add meshes
  78621. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78622. */
  78623. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78624. var _this = this;
  78625. var meshName;
  78626. // Hand
  78627. if (this.hand === 'left') {
  78628. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78629. }
  78630. else { // Right is the default if no hand is specified
  78631. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78632. }
  78633. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78634. /*
  78635. Parent Mesh name: oculus_touch_left
  78636. - body
  78637. - trigger
  78638. - thumbstick
  78639. - grip
  78640. - button_y
  78641. - button_x
  78642. - button_enter
  78643. */
  78644. _this._defaultModel = newMeshes[1];
  78645. _this.attachToMesh(_this._defaultModel);
  78646. if (meshLoaded) {
  78647. meshLoaded(_this._defaultModel);
  78648. }
  78649. });
  78650. };
  78651. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  78652. /**
  78653. * Fired when the A button on this controller is modified
  78654. */
  78655. get: function () {
  78656. if (this.hand === 'right') {
  78657. return this.onMainButtonStateChangedObservable;
  78658. }
  78659. else {
  78660. throw new Error('No A button on left hand');
  78661. }
  78662. },
  78663. enumerable: true,
  78664. configurable: true
  78665. });
  78666. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  78667. /**
  78668. * Fired when the B button on this controller is modified
  78669. */
  78670. get: function () {
  78671. if (this.hand === 'right') {
  78672. return this.onSecondaryButtonStateChangedObservable;
  78673. }
  78674. else {
  78675. throw new Error('No B button on left hand');
  78676. }
  78677. },
  78678. enumerable: true,
  78679. configurable: true
  78680. });
  78681. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  78682. /**
  78683. * Fired when the X button on this controller is modified
  78684. */
  78685. get: function () {
  78686. if (this.hand === 'left') {
  78687. return this.onMainButtonStateChangedObservable;
  78688. }
  78689. else {
  78690. throw new Error('No X button on right hand');
  78691. }
  78692. },
  78693. enumerable: true,
  78694. configurable: true
  78695. });
  78696. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  78697. /**
  78698. * Fired when the Y button on this controller is modified
  78699. */
  78700. get: function () {
  78701. if (this.hand === 'left') {
  78702. return this.onSecondaryButtonStateChangedObservable;
  78703. }
  78704. else {
  78705. throw new Error('No Y button on right hand');
  78706. }
  78707. },
  78708. enumerable: true,
  78709. configurable: true
  78710. });
  78711. /**
  78712. * Called once for each button that changed state since the last frame
  78713. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  78714. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  78715. * 2) secondary trigger (same)
  78716. * 3) A (right) X (left), touch, pressed = value
  78717. * 4) B / Y
  78718. * 5) thumb rest
  78719. * @param buttonIdx Which button index changed
  78720. * @param state New state of the button
  78721. * @param changes Which properties on the state changed since last frame
  78722. */
  78723. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78724. var notifyObject = state; //{ state: state, changes: changes };
  78725. var triggerDirection = this.hand === 'right' ? -1 : 1;
  78726. switch (buttonIdx) {
  78727. case 0:
  78728. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78729. return;
  78730. case 1: // index trigger
  78731. if (this._defaultModel) {
  78732. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  78733. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  78734. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  78735. }
  78736. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78737. return;
  78738. case 2: // secondary trigger
  78739. if (this._defaultModel) {
  78740. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  78741. }
  78742. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  78743. return;
  78744. case 3:
  78745. if (this._defaultModel) {
  78746. if (notifyObject.pressed) {
  78747. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  78748. }
  78749. else {
  78750. (this._defaultModel.getChildren()[1]).position.y = 0;
  78751. }
  78752. }
  78753. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78754. return;
  78755. case 4:
  78756. if (this._defaultModel) {
  78757. if (notifyObject.pressed) {
  78758. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78759. }
  78760. else {
  78761. (this._defaultModel.getChildren()[2]).position.y = 0;
  78762. }
  78763. }
  78764. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78765. return;
  78766. case 5:
  78767. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  78768. return;
  78769. }
  78770. };
  78771. /**
  78772. * Base Url for the controller model.
  78773. */
  78774. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  78775. /**
  78776. * File name for the left controller model.
  78777. */
  78778. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  78779. /**
  78780. * File name for the right controller model.
  78781. */
  78782. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  78783. return OculusTouchController;
  78784. }(BABYLON.WebVRController));
  78785. BABYLON.OculusTouchController = OculusTouchController;
  78786. })(BABYLON || (BABYLON = {}));
  78787. //# sourceMappingURL=babylon.oculusTouchController.js.map
  78788. var BABYLON;
  78789. (function (BABYLON) {
  78790. /**
  78791. * Vive Controller
  78792. */
  78793. var ViveController = /** @class */ (function (_super) {
  78794. __extends(ViveController, _super);
  78795. /**
  78796. * Creates a new ViveController from a gamepad
  78797. * @param vrGamepad the gamepad that the controller should be created from
  78798. */
  78799. function ViveController(vrGamepad) {
  78800. var _this = _super.call(this, vrGamepad) || this;
  78801. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  78802. _this._invertLeftStickY = true;
  78803. return _this;
  78804. }
  78805. /**
  78806. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78807. * @param scene scene in which to add meshes
  78808. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78809. */
  78810. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78811. var _this = this;
  78812. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  78813. /*
  78814. Parent Mesh name: ViveWand
  78815. - body
  78816. - r_gripper
  78817. - l_gripper
  78818. - menu_button
  78819. - system_button
  78820. - trackpad
  78821. - trigger
  78822. - LED
  78823. */
  78824. _this._defaultModel = newMeshes[1];
  78825. _this.attachToMesh(_this._defaultModel);
  78826. if (meshLoaded) {
  78827. meshLoaded(_this._defaultModel);
  78828. }
  78829. });
  78830. };
  78831. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  78832. /**
  78833. * Fired when the left button on this controller is modified
  78834. */
  78835. get: function () {
  78836. return this.onMainButtonStateChangedObservable;
  78837. },
  78838. enumerable: true,
  78839. configurable: true
  78840. });
  78841. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  78842. /**
  78843. * Fired when the right button on this controller is modified
  78844. */
  78845. get: function () {
  78846. return this.onMainButtonStateChangedObservable;
  78847. },
  78848. enumerable: true,
  78849. configurable: true
  78850. });
  78851. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  78852. /**
  78853. * Fired when the menu button on this controller is modified
  78854. */
  78855. get: function () {
  78856. return this.onSecondaryButtonStateChangedObservable;
  78857. },
  78858. enumerable: true,
  78859. configurable: true
  78860. });
  78861. /**
  78862. * Called once for each button that changed state since the last frame
  78863. * Vive mapping:
  78864. * 0: touchpad
  78865. * 1: trigger
  78866. * 2: left AND right buttons
  78867. * 3: menu button
  78868. * @param buttonIdx Which button index changed
  78869. * @param state New state of the button
  78870. * @param changes Which properties on the state changed since last frame
  78871. */
  78872. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78873. var notifyObject = state; //{ state: state, changes: changes };
  78874. switch (buttonIdx) {
  78875. case 0:
  78876. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78877. return;
  78878. case 1: // index trigger
  78879. if (this._defaultModel) {
  78880. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  78881. }
  78882. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78883. return;
  78884. case 2: // left AND right button
  78885. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78886. return;
  78887. case 3:
  78888. if (this._defaultModel) {
  78889. if (notifyObject.pressed) {
  78890. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78891. }
  78892. else {
  78893. (this._defaultModel.getChildren()[2]).position.y = 0;
  78894. }
  78895. }
  78896. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78897. return;
  78898. }
  78899. };
  78900. /**
  78901. * Base Url for the controller model.
  78902. */
  78903. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78904. /**
  78905. * File name for the controller model.
  78906. */
  78907. ViveController.MODEL_FILENAME = 'wand.babylon';
  78908. return ViveController;
  78909. }(BABYLON.WebVRController));
  78910. BABYLON.ViveController = ViveController;
  78911. })(BABYLON || (BABYLON = {}));
  78912. //# sourceMappingURL=babylon.viveController.js.map
  78913. var BABYLON;
  78914. (function (BABYLON) {
  78915. /**
  78916. * Generic Controller
  78917. */
  78918. var GenericController = /** @class */ (function (_super) {
  78919. __extends(GenericController, _super);
  78920. /**
  78921. * Creates a new GenericController from a gamepad
  78922. * @param vrGamepad the gamepad that the controller should be created from
  78923. */
  78924. function GenericController(vrGamepad) {
  78925. return _super.call(this, vrGamepad) || this;
  78926. }
  78927. /**
  78928. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78929. * @param scene scene in which to add meshes
  78930. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78931. */
  78932. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78933. var _this = this;
  78934. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78935. _this._defaultModel = newMeshes[1];
  78936. _this.attachToMesh(_this._defaultModel);
  78937. if (meshLoaded) {
  78938. meshLoaded(_this._defaultModel);
  78939. }
  78940. });
  78941. };
  78942. /**
  78943. * Called once for each button that changed state since the last frame
  78944. * @param buttonIdx Which button index changed
  78945. * @param state New state of the button
  78946. * @param changes Which properties on the state changed since last frame
  78947. */
  78948. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78949. console.log("Button id: " + buttonIdx + "state: ");
  78950. console.dir(state);
  78951. };
  78952. /**
  78953. * Base Url for the controller model.
  78954. */
  78955. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78956. /**
  78957. * File name for the controller model.
  78958. */
  78959. GenericController.MODEL_FILENAME = 'generic.babylon';
  78960. return GenericController;
  78961. }(BABYLON.WebVRController));
  78962. BABYLON.GenericController = GenericController;
  78963. })(BABYLON || (BABYLON = {}));
  78964. //# sourceMappingURL=babylon.genericController.js.map
  78965. var BABYLON;
  78966. (function (BABYLON) {
  78967. /**
  78968. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78969. */
  78970. var LoadedMeshInfo = /** @class */ (function () {
  78971. function LoadedMeshInfo() {
  78972. /**
  78973. * Map of the button meshes contained in the controller
  78974. */
  78975. this.buttonMeshes = {};
  78976. /**
  78977. * Map of the axis meshes contained in the controller
  78978. */
  78979. this.axisMeshes = {};
  78980. }
  78981. return LoadedMeshInfo;
  78982. }());
  78983. /**
  78984. * Defines the WindowsMotionController object that the state of the windows motion controller
  78985. */
  78986. var WindowsMotionController = /** @class */ (function (_super) {
  78987. __extends(WindowsMotionController, _super);
  78988. /**
  78989. * Creates a new WindowsMotionController from a gamepad
  78990. * @param vrGamepad the gamepad that the controller should be created from
  78991. */
  78992. function WindowsMotionController(vrGamepad) {
  78993. var _this = _super.call(this, vrGamepad) || this;
  78994. _this._mapping = {
  78995. // Semantic button names
  78996. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  78997. // A mapping of the button name to glTF model node name
  78998. // that should be transformed by button value.
  78999. buttonMeshNames: {
  79000. 'trigger': 'SELECT',
  79001. 'menu': 'MENU',
  79002. 'grip': 'GRASP',
  79003. 'thumbstick': 'THUMBSTICK_PRESS',
  79004. 'trackpad': 'TOUCHPAD_PRESS'
  79005. },
  79006. // This mapping is used to translate from the Motion Controller to Babylon semantics
  79007. buttonObservableNames: {
  79008. 'trigger': 'onTriggerStateChangedObservable',
  79009. 'menu': 'onSecondaryButtonStateChangedObservable',
  79010. 'grip': 'onMainButtonStateChangedObservable',
  79011. 'thumbstick': 'onPadStateChangedObservable',
  79012. 'trackpad': 'onTrackpadChangedObservable'
  79013. },
  79014. // A mapping of the axis name to glTF model node name
  79015. // that should be transformed by axis value.
  79016. // This array mirrors the browserGamepad.axes array, such that
  79017. // the mesh corresponding to axis 0 is in this array index 0.
  79018. axisMeshNames: [
  79019. 'THUMBSTICK_X',
  79020. 'THUMBSTICK_Y',
  79021. 'TOUCHPAD_TOUCH_X',
  79022. 'TOUCHPAD_TOUCH_Y'
  79023. ],
  79024. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  79025. };
  79026. /**
  79027. * Fired when the trackpad on this controller is clicked
  79028. */
  79029. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  79030. /**
  79031. * Fired when the trackpad on this controller is modified
  79032. */
  79033. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  79034. /**
  79035. * The current x and y values of this controller's trackpad
  79036. */
  79037. _this.trackpad = { x: 0, y: 0 };
  79038. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  79039. _this._loadedMeshInfo = null;
  79040. return _this;
  79041. }
  79042. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  79043. /**
  79044. * Fired when the trigger on this controller is modified
  79045. */
  79046. get: function () {
  79047. return this.onTriggerStateChangedObservable;
  79048. },
  79049. enumerable: true,
  79050. configurable: true
  79051. });
  79052. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  79053. /**
  79054. * Fired when the menu button on this controller is modified
  79055. */
  79056. get: function () {
  79057. return this.onSecondaryButtonStateChangedObservable;
  79058. },
  79059. enumerable: true,
  79060. configurable: true
  79061. });
  79062. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  79063. /**
  79064. * Fired when the grip button on this controller is modified
  79065. */
  79066. get: function () {
  79067. return this.onMainButtonStateChangedObservable;
  79068. },
  79069. enumerable: true,
  79070. configurable: true
  79071. });
  79072. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  79073. /**
  79074. * Fired when the thumbstick button on this controller is modified
  79075. */
  79076. get: function () {
  79077. return this.onPadStateChangedObservable;
  79078. },
  79079. enumerable: true,
  79080. configurable: true
  79081. });
  79082. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  79083. /**
  79084. * Fired when the touchpad button on this controller is modified
  79085. */
  79086. get: function () {
  79087. return this.onTrackpadChangedObservable;
  79088. },
  79089. enumerable: true,
  79090. configurable: true
  79091. });
  79092. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  79093. /**
  79094. * Fired when the touchpad values on this controller are modified
  79095. */
  79096. get: function () {
  79097. return this.onTrackpadValuesChangedObservable;
  79098. },
  79099. enumerable: true,
  79100. configurable: true
  79101. });
  79102. WindowsMotionController.prototype._updateTrackpad = function () {
  79103. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  79104. this.trackpad.x = this.browserGamepad["axes"][2];
  79105. this.trackpad.y = this.browserGamepad["axes"][3];
  79106. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  79107. }
  79108. };
  79109. /**
  79110. * Called once per frame by the engine.
  79111. */
  79112. WindowsMotionController.prototype.update = function () {
  79113. _super.prototype.update.call(this);
  79114. if (this.browserGamepad.axes) {
  79115. this._updateTrackpad();
  79116. // Only need to animate axes if there is a loaded mesh
  79117. if (this._loadedMeshInfo) {
  79118. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  79119. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  79120. }
  79121. }
  79122. }
  79123. };
  79124. /**
  79125. * Called once for each button that changed state since the last frame
  79126. * @param buttonIdx Which button index changed
  79127. * @param state New state of the button
  79128. * @param changes Which properties on the state changed since last frame
  79129. */
  79130. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79131. var buttonName = this._mapping.buttons[buttonIdx];
  79132. if (!buttonName) {
  79133. return;
  79134. }
  79135. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  79136. this._updateTrackpad();
  79137. // Only emit events for buttons that we know how to map from index to name
  79138. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  79139. if (observable) {
  79140. observable.notifyObservers(state);
  79141. }
  79142. this._lerpButtonTransform(buttonName, state.value);
  79143. };
  79144. /**
  79145. * Moves the buttons on the controller mesh based on their current state
  79146. * @param buttonName the name of the button to move
  79147. * @param buttonValue the value of the button which determines the buttons new position
  79148. */
  79149. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  79150. // If there is no loaded mesh, there is nothing to transform.
  79151. if (!this._loadedMeshInfo) {
  79152. return;
  79153. }
  79154. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  79155. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79156. return;
  79157. }
  79158. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  79159. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  79160. };
  79161. /**
  79162. * Moves the axis on the controller mesh based on its current state
  79163. * @param axis the index of the axis
  79164. * @param axisValue the value of the axis which determines the meshes new position
  79165. * @hidden
  79166. */
  79167. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  79168. if (!this._loadedMeshInfo) {
  79169. return;
  79170. }
  79171. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  79172. if (!meshInfo) {
  79173. return;
  79174. }
  79175. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79176. return;
  79177. }
  79178. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  79179. var lerpValue = axisValue * 0.5 + 0.5;
  79180. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  79181. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  79182. };
  79183. /**
  79184. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79185. * @param scene scene in which to add meshes
  79186. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79187. */
  79188. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  79189. var _this = this;
  79190. if (forceDefault === void 0) { forceDefault = false; }
  79191. var path;
  79192. var filename;
  79193. // Checking if GLB loader is present
  79194. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  79195. // Determine the device specific folder based on the ID suffix
  79196. var device = 'default';
  79197. if (this.id && !forceDefault) {
  79198. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  79199. device = ((match && match[0]) || device);
  79200. }
  79201. // Hand
  79202. if (this.hand === 'left') {
  79203. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  79204. }
  79205. else { // Right is the default if no hand is specified
  79206. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  79207. }
  79208. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  79209. }
  79210. else {
  79211. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  79212. path = BABYLON.GenericController.MODEL_BASE_URL;
  79213. filename = BABYLON.GenericController.MODEL_FILENAME;
  79214. }
  79215. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  79216. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  79217. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  79218. if (!_this._loadedMeshInfo) {
  79219. return;
  79220. }
  79221. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  79222. _this.attachToMesh(_this._defaultModel);
  79223. if (meshLoaded) {
  79224. meshLoaded(_this._defaultModel);
  79225. }
  79226. }, null, function (scene, message) {
  79227. BABYLON.Tools.Log(message);
  79228. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  79229. if (!forceDefault) {
  79230. _this.initControllerMesh(scene, meshLoaded, true);
  79231. }
  79232. });
  79233. };
  79234. /**
  79235. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  79236. * can be transformed by button presses and axes values, based on this._mapping.
  79237. *
  79238. * @param scene scene in which the meshes exist
  79239. * @param meshes list of meshes that make up the controller model to process
  79240. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  79241. */
  79242. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  79243. var loadedMeshInfo = null;
  79244. // Create a new mesh to contain the glTF hierarchy
  79245. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  79246. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  79247. var childMesh = null;
  79248. for (var i = 0; i < meshes.length; i++) {
  79249. var mesh = meshes[i];
  79250. if (!mesh.parent) {
  79251. // Exclude controller meshes from picking results
  79252. mesh.isPickable = false;
  79253. // Handle root node, attach to the new parentMesh
  79254. childMesh = mesh;
  79255. break;
  79256. }
  79257. }
  79258. if (childMesh) {
  79259. childMesh.setParent(parentMesh);
  79260. // Create our mesh info. Note that this method will always return non-null.
  79261. loadedMeshInfo = this.createMeshInfo(parentMesh);
  79262. }
  79263. else {
  79264. BABYLON.Tools.Warn('Could not find root node in model file.');
  79265. }
  79266. return loadedMeshInfo;
  79267. };
  79268. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  79269. var loadedMeshInfo = new LoadedMeshInfo();
  79270. var i;
  79271. loadedMeshInfo.rootNode = rootNode;
  79272. // Reset the caches
  79273. loadedMeshInfo.buttonMeshes = {};
  79274. loadedMeshInfo.axisMeshes = {};
  79275. // Button Meshes
  79276. for (i = 0; i < this._mapping.buttons.length; i++) {
  79277. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  79278. if (!buttonMeshName) {
  79279. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  79280. continue;
  79281. }
  79282. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  79283. if (!buttonMesh) {
  79284. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  79285. continue;
  79286. }
  79287. var buttonMeshInfo = {
  79288. index: i,
  79289. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  79290. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  79291. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  79292. };
  79293. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  79294. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  79295. }
  79296. else {
  79297. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  79298. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  79299. '(VALUE: ' + !!buttonMeshInfo.value +
  79300. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  79301. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  79302. ')');
  79303. }
  79304. }
  79305. // Axis Meshes
  79306. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  79307. var axisMeshName = this._mapping.axisMeshNames[i];
  79308. if (!axisMeshName) {
  79309. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  79310. continue;
  79311. }
  79312. var axisMesh = getChildByName(rootNode, axisMeshName);
  79313. if (!axisMesh) {
  79314. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  79315. continue;
  79316. }
  79317. var axisMeshInfo = {
  79318. index: i,
  79319. value: getImmediateChildByName(axisMesh, 'VALUE'),
  79320. min: getImmediateChildByName(axisMesh, 'MIN'),
  79321. max: getImmediateChildByName(axisMesh, 'MAX')
  79322. };
  79323. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  79324. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  79325. }
  79326. else {
  79327. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  79328. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  79329. '(VALUE: ' + !!axisMeshInfo.value +
  79330. ', MIN: ' + !!axisMeshInfo.min +
  79331. ', MAX:' + !!axisMeshInfo.max +
  79332. ')');
  79333. }
  79334. }
  79335. // Pointing Ray
  79336. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  79337. if (!loadedMeshInfo.pointingPoseNode) {
  79338. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  79339. }
  79340. else {
  79341. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  79342. }
  79343. return loadedMeshInfo;
  79344. // Look through all children recursively. This will return null if no mesh exists with the given name.
  79345. function getChildByName(node, name) {
  79346. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  79347. }
  79348. // Look through only immediate children. This will return null if no mesh exists with the given name.
  79349. function getImmediateChildByName(node, name) {
  79350. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  79351. }
  79352. };
  79353. /**
  79354. * Gets the ray of the controller in the direction the controller is pointing
  79355. * @param length the length the resulting ray should be
  79356. * @returns a ray in the direction the controller is pointing
  79357. */
  79358. WindowsMotionController.prototype.getForwardRay = function (length) {
  79359. if (length === void 0) { length = 100; }
  79360. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  79361. return _super.prototype.getForwardRay.call(this, length);
  79362. }
  79363. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  79364. var origin = m.getTranslation();
  79365. var forward = new BABYLON.Vector3(0, 0, -1);
  79366. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79367. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79368. return new BABYLON.Ray(origin, direction, length);
  79369. };
  79370. /**
  79371. * Disposes of the controller
  79372. */
  79373. WindowsMotionController.prototype.dispose = function () {
  79374. _super.prototype.dispose.call(this);
  79375. this.onTrackpadChangedObservable.clear();
  79376. };
  79377. /**
  79378. * The base url used to load the left and right controller models
  79379. */
  79380. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  79381. /**
  79382. * The name of the left controller model file
  79383. */
  79384. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  79385. /**
  79386. * The name of the right controller model file
  79387. */
  79388. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  79389. /**
  79390. * The controller name prefix for this controller type
  79391. */
  79392. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  79393. /**
  79394. * The controller id pattern for this controller type
  79395. */
  79396. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  79397. return WindowsMotionController;
  79398. }(BABYLON.WebVRController));
  79399. BABYLON.WindowsMotionController = WindowsMotionController;
  79400. })(BABYLON || (BABYLON = {}));
  79401. //# sourceMappingURL=babylon.windowsMotionController.js.map
  79402. var BABYLON;
  79403. (function (BABYLON) {
  79404. /**
  79405. * Gear VR Controller
  79406. */
  79407. var GearVRController = /** @class */ (function (_super) {
  79408. __extends(GearVRController, _super);
  79409. /**
  79410. * Creates a new GearVRController from a gamepad
  79411. * @param vrGamepad the gamepad that the controller should be created from
  79412. */
  79413. function GearVRController(vrGamepad) {
  79414. var _this = _super.call(this, vrGamepad) || this;
  79415. _this._buttonIndexToObservableNameMap = [
  79416. 'onTrackpadChangedObservable',
  79417. 'onTriggerStateChangedObservable' // Trigger
  79418. ];
  79419. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  79420. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  79421. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  79422. _this._disableTrackPosition(_this._calculatedPosition);
  79423. return _this;
  79424. }
  79425. /**
  79426. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79427. * @param scene scene in which to add meshes
  79428. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79429. */
  79430. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79431. var _this = this;
  79432. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  79433. // Offset the controller so it will rotate around the users wrist
  79434. var mesh = new BABYLON.Mesh("", scene);
  79435. newMeshes[1].parent = mesh;
  79436. newMeshes[1].position.z = -0.15;
  79437. _this._defaultModel = mesh;
  79438. _this.attachToMesh(_this._defaultModel);
  79439. if (meshLoaded) {
  79440. meshLoaded(_this._defaultModel);
  79441. }
  79442. });
  79443. };
  79444. /**
  79445. * Called once for each button that changed state since the last frame
  79446. * @param buttonIdx Which button index changed
  79447. * @param state New state of the button
  79448. * @param changes Which properties on the state changed since last frame
  79449. */
  79450. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79451. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  79452. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  79453. // Only emit events for buttons that we know how to map from index to observable
  79454. var observable = this[observableName];
  79455. if (observable) {
  79456. observable.notifyObservers(state);
  79457. }
  79458. }
  79459. };
  79460. /**
  79461. * Base Url for the controller model.
  79462. */
  79463. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79464. /**
  79465. * File name for the controller model.
  79466. */
  79467. GearVRController.MODEL_FILENAME = 'generic.babylon';
  79468. /**
  79469. * Gamepad Id prefix used to identify this controller.
  79470. */
  79471. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  79472. return GearVRController;
  79473. }(BABYLON.WebVRController));
  79474. BABYLON.GearVRController = GearVRController;
  79475. })(BABYLON || (BABYLON = {}));
  79476. //# sourceMappingURL=babylon.gearVRController.js.map
  79477. var BABYLON;
  79478. (function (BABYLON) {
  79479. /**
  79480. * Google Daydream controller
  79481. */
  79482. var DaydreamController = /** @class */ (function (_super) {
  79483. __extends(DaydreamController, _super);
  79484. /**
  79485. * Creates a new DaydreamController from a gamepad
  79486. * @param vrGamepad the gamepad that the controller should be created from
  79487. */
  79488. function DaydreamController(vrGamepad) {
  79489. var _this = _super.call(this, vrGamepad) || this;
  79490. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  79491. return _this;
  79492. }
  79493. /**
  79494. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79495. * @param scene scene in which to add meshes
  79496. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79497. */
  79498. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79499. var _this = this;
  79500. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  79501. _this._defaultModel = newMeshes[1];
  79502. _this.attachToMesh(_this._defaultModel);
  79503. if (meshLoaded) {
  79504. meshLoaded(_this._defaultModel);
  79505. }
  79506. });
  79507. };
  79508. /**
  79509. * Called once for each button that changed state since the last frame
  79510. * @param buttonIdx Which button index changed
  79511. * @param state New state of the button
  79512. * @param changes Which properties on the state changed since last frame
  79513. */
  79514. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79515. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79516. if (buttonIdx === 0) {
  79517. var observable = this.onTriggerStateChangedObservable;
  79518. if (observable) {
  79519. observable.notifyObservers(state);
  79520. }
  79521. }
  79522. else {
  79523. // If the app or home buttons are ever made available
  79524. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79525. }
  79526. };
  79527. /**
  79528. * Base Url for the controller model.
  79529. */
  79530. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79531. /**
  79532. * File name for the controller model.
  79533. */
  79534. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79535. /**
  79536. * Gamepad Id prefix used to identify Daydream Controller.
  79537. */
  79538. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79539. return DaydreamController;
  79540. }(BABYLON.WebVRController));
  79541. BABYLON.DaydreamController = DaydreamController;
  79542. })(BABYLON || (BABYLON = {}));
  79543. //# sourceMappingURL=babylon.daydreamController.js.map
  79544. var BABYLON;
  79545. (function (BABYLON) {
  79546. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79547. get: function () {
  79548. if (!this._gamepadManager) {
  79549. this._gamepadManager = new BABYLON.GamepadManager(this);
  79550. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79551. if (!component) {
  79552. component = new GamepadSystemSceneComponent(this);
  79553. this._addComponent(component);
  79554. }
  79555. }
  79556. return this._gamepadManager;
  79557. },
  79558. enumerable: true,
  79559. configurable: true
  79560. });
  79561. /**
  79562. * Adds a gamepad to the free camera inputs manager
  79563. */
  79564. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79565. this.add(new BABYLON.FreeCameraGamepadInput());
  79566. return this;
  79567. };
  79568. /**
  79569. * Adds a gamepad to the arc rotate camera inputs manager
  79570. */
  79571. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79572. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79573. return this;
  79574. };
  79575. /**
  79576. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79577. */
  79578. var GamepadSystemSceneComponent = /** @class */ (function () {
  79579. /**
  79580. * Creates a new instance of the component for the given scene
  79581. * @param scene Defines the scene to register the component in
  79582. */
  79583. function GamepadSystemSceneComponent(scene) {
  79584. /**
  79585. * The component name helpfull to identify the component in the list of scene components.
  79586. */
  79587. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79588. this.scene = scene;
  79589. }
  79590. /**
  79591. * Registers the component in a given scene
  79592. */
  79593. GamepadSystemSceneComponent.prototype.register = function () {
  79594. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79595. };
  79596. /**
  79597. * Rebuilds the elements related to this component in case of
  79598. * context lost for instance.
  79599. */
  79600. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79601. // Nothing to do for gamepads
  79602. };
  79603. /**
  79604. * Disposes the component and the associated ressources
  79605. */
  79606. GamepadSystemSceneComponent.prototype.dispose = function () {
  79607. var gamepadManager = this.scene._gamepadManager;
  79608. if (gamepadManager) {
  79609. gamepadManager.dispose();
  79610. this.scene._gamepadManager = null;
  79611. }
  79612. };
  79613. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79614. var gamepadManager = this.scene._gamepadManager;
  79615. if (gamepadManager && gamepadManager._isMonitoring) {
  79616. gamepadManager._checkGamepadsStatus();
  79617. }
  79618. };
  79619. return GamepadSystemSceneComponent;
  79620. }());
  79621. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79622. })(BABYLON || (BABYLON = {}));
  79623. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79624. var BABYLON;
  79625. (function (BABYLON) {
  79626. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79627. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79628. });
  79629. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79630. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79631. });
  79632. /**
  79633. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79634. * an arc rotate version arcFollowCamera are available.
  79635. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79636. */
  79637. var FollowCamera = /** @class */ (function (_super) {
  79638. __extends(FollowCamera, _super);
  79639. /**
  79640. * Instantiates the follow camera.
  79641. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79642. * @param name Define the name of the camera in the scene
  79643. * @param position Define the position of the camera
  79644. * @param scene Define the scene the camera belong to
  79645. * @param lockedTarget Define the target of the camera
  79646. */
  79647. function FollowCamera(name, position, scene, lockedTarget) {
  79648. if (lockedTarget === void 0) { lockedTarget = null; }
  79649. var _this = _super.call(this, name, position, scene) || this;
  79650. /**
  79651. * Distance the follow camera should follow an object at
  79652. */
  79653. _this.radius = 12;
  79654. /**
  79655. * Define a rotation offset between the camera and the object it follows
  79656. */
  79657. _this.rotationOffset = 0;
  79658. /**
  79659. * Define a height offset between the camera and the object it follows.
  79660. * It can help following an object from the top (like a car chaing a plane)
  79661. */
  79662. _this.heightOffset = 4;
  79663. /**
  79664. * Define how fast the camera can accelerate to follow it s target.
  79665. */
  79666. _this.cameraAcceleration = 0.05;
  79667. /**
  79668. * Define the speed limit of the camera following an object.
  79669. */
  79670. _this.maxCameraSpeed = 20;
  79671. _this.lockedTarget = lockedTarget;
  79672. return _this;
  79673. }
  79674. FollowCamera.prototype._follow = function (cameraTarget) {
  79675. if (!cameraTarget)
  79676. return;
  79677. var yRotation;
  79678. if (cameraTarget.rotationQuaternion) {
  79679. var rotMatrix = new BABYLON.Matrix();
  79680. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  79681. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  79682. }
  79683. else {
  79684. yRotation = cameraTarget.rotation.y;
  79685. }
  79686. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  79687. var targetPosition = cameraTarget.getAbsolutePosition();
  79688. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  79689. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  79690. var dx = targetX - this.position.x;
  79691. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  79692. var dz = (targetZ) - this.position.z;
  79693. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  79694. var vy = dy * this.cameraAcceleration;
  79695. var vz = dz * this.cameraAcceleration * 2;
  79696. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  79697. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79698. }
  79699. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  79700. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79701. }
  79702. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  79703. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79704. }
  79705. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  79706. this.setTarget(targetPosition);
  79707. };
  79708. /** @hidden */
  79709. FollowCamera.prototype._checkInputs = function () {
  79710. _super.prototype._checkInputs.call(this);
  79711. if (this.lockedTarget) {
  79712. this._follow(this.lockedTarget);
  79713. }
  79714. };
  79715. /**
  79716. * Gets the camera class name.
  79717. * @returns the class name
  79718. */
  79719. FollowCamera.prototype.getClassName = function () {
  79720. return "FollowCamera";
  79721. };
  79722. __decorate([
  79723. BABYLON.serialize()
  79724. ], FollowCamera.prototype, "radius", void 0);
  79725. __decorate([
  79726. BABYLON.serialize()
  79727. ], FollowCamera.prototype, "rotationOffset", void 0);
  79728. __decorate([
  79729. BABYLON.serialize()
  79730. ], FollowCamera.prototype, "heightOffset", void 0);
  79731. __decorate([
  79732. BABYLON.serialize()
  79733. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  79734. __decorate([
  79735. BABYLON.serialize()
  79736. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  79737. __decorate([
  79738. BABYLON.serializeAsMeshReference("lockedTargetId")
  79739. ], FollowCamera.prototype, "lockedTarget", void 0);
  79740. return FollowCamera;
  79741. }(BABYLON.TargetCamera));
  79742. BABYLON.FollowCamera = FollowCamera;
  79743. /**
  79744. * Arc Rotate version of the follow camera.
  79745. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  79746. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79747. */
  79748. var ArcFollowCamera = /** @class */ (function (_super) {
  79749. __extends(ArcFollowCamera, _super);
  79750. /**
  79751. * Instantiates a new ArcFollowCamera
  79752. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79753. * @param name Define the name of the camera
  79754. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  79755. * @param beta Define the rotation angle of the camera around the elevation axis
  79756. * @param radius Define the radius of the camera from its target point
  79757. * @param target Define the target of the camera
  79758. * @param scene Define the scene the camera belongs to
  79759. */
  79760. function ArcFollowCamera(name,
  79761. /** The longitudinal angle of the camera */
  79762. alpha,
  79763. /** The latitudinal angle of the camera */
  79764. beta,
  79765. /** The radius of the camera from its target */
  79766. radius,
  79767. /** Define the camera target (the messh it should follow) */
  79768. target, scene) {
  79769. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  79770. _this.alpha = alpha;
  79771. _this.beta = beta;
  79772. _this.radius = radius;
  79773. _this.target = target;
  79774. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  79775. _this._follow();
  79776. return _this;
  79777. }
  79778. ArcFollowCamera.prototype._follow = function () {
  79779. if (!this.target) {
  79780. return;
  79781. }
  79782. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  79783. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  79784. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  79785. var targetPosition = this.target.getAbsolutePosition();
  79786. this.position = targetPosition.add(this._cartesianCoordinates);
  79787. this.setTarget(targetPosition);
  79788. };
  79789. /** @hidden */
  79790. ArcFollowCamera.prototype._checkInputs = function () {
  79791. _super.prototype._checkInputs.call(this);
  79792. this._follow();
  79793. };
  79794. /**
  79795. * Returns the class name of the object.
  79796. * It is mostly used internally for serialization purposes.
  79797. */
  79798. ArcFollowCamera.prototype.getClassName = function () {
  79799. return "ArcFollowCamera";
  79800. };
  79801. return ArcFollowCamera;
  79802. }(BABYLON.TargetCamera));
  79803. BABYLON.ArcFollowCamera = ArcFollowCamera;
  79804. })(BABYLON || (BABYLON = {}));
  79805. //# sourceMappingURL=babylon.followCamera.js.map
  79806. var BABYLON;
  79807. (function (BABYLON) {
  79808. /**
  79809. * 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,
  79810. * which still works and will still be found in many Playgrounds.
  79811. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79812. */
  79813. var UniversalCamera = /** @class */ (function (_super) {
  79814. __extends(UniversalCamera, _super);
  79815. /**
  79816. * 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,
  79817. * which still works and will still be found in many Playgrounds.
  79818. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79819. * @param name Define the name of the camera in the scene
  79820. * @param position Define the start position of the camera in the scene
  79821. * @param scene Define the scene the camera belongs to
  79822. */
  79823. function UniversalCamera(name, position, scene) {
  79824. var _this = _super.call(this, name, position, scene) || this;
  79825. _this.inputs.addGamepad();
  79826. return _this;
  79827. }
  79828. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  79829. /**
  79830. * Defines the gamepad rotation sensiblity.
  79831. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79832. */
  79833. get: function () {
  79834. var gamepad = this.inputs.attached["gamepad"];
  79835. if (gamepad)
  79836. return gamepad.gamepadAngularSensibility;
  79837. return 0;
  79838. },
  79839. set: function (value) {
  79840. var gamepad = this.inputs.attached["gamepad"];
  79841. if (gamepad)
  79842. gamepad.gamepadAngularSensibility = value;
  79843. },
  79844. enumerable: true,
  79845. configurable: true
  79846. });
  79847. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  79848. /**
  79849. * Defines the gamepad move sensiblity.
  79850. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79851. */
  79852. get: function () {
  79853. var gamepad = this.inputs.attached["gamepad"];
  79854. if (gamepad)
  79855. return gamepad.gamepadMoveSensibility;
  79856. return 0;
  79857. },
  79858. set: function (value) {
  79859. var gamepad = this.inputs.attached["gamepad"];
  79860. if (gamepad)
  79861. gamepad.gamepadMoveSensibility = value;
  79862. },
  79863. enumerable: true,
  79864. configurable: true
  79865. });
  79866. /**
  79867. * Gets the current object class name.
  79868. * @return the class name
  79869. */
  79870. UniversalCamera.prototype.getClassName = function () {
  79871. return "UniversalCamera";
  79872. };
  79873. return UniversalCamera;
  79874. }(BABYLON.TouchCamera));
  79875. BABYLON.UniversalCamera = UniversalCamera;
  79876. })(BABYLON || (BABYLON = {}));
  79877. //# sourceMappingURL=babylon.universalCamera.js.map
  79878. var BABYLON;
  79879. (function (BABYLON) {
  79880. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79881. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79882. });
  79883. /**
  79884. * This represents a FPS type of camera. This is only here for back compat purpose.
  79885. * Please use the UniversalCamera instead as both are identical.
  79886. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79887. */
  79888. var GamepadCamera = /** @class */ (function (_super) {
  79889. __extends(GamepadCamera, _super);
  79890. /**
  79891. * Instantiates a new Gamepad Camera
  79892. * This represents a FPS type of camera. This is only here for back compat purpose.
  79893. * Please use the UniversalCamera instead as both are identical.
  79894. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79895. * @param name Define the name of the camera in the scene
  79896. * @param position Define the start position of the camera in the scene
  79897. * @param scene Define the scene the camera belongs to
  79898. */
  79899. function GamepadCamera(name, position, scene) {
  79900. return _super.call(this, name, position, scene) || this;
  79901. }
  79902. /**
  79903. * Gets the current object class name.
  79904. * @return the class name
  79905. */
  79906. GamepadCamera.prototype.getClassName = function () {
  79907. return "GamepadCamera";
  79908. };
  79909. return GamepadCamera;
  79910. }(BABYLON.UniversalCamera));
  79911. BABYLON.GamepadCamera = GamepadCamera;
  79912. })(BABYLON || (BABYLON = {}));
  79913. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79914. var BABYLON;
  79915. (function (BABYLON) {
  79916. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79917. function PostProcessRenderPipelineManager() {
  79918. this._renderPipelines = {};
  79919. }
  79920. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79921. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79922. };
  79923. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79924. if (unique === void 0) { unique = false; }
  79925. var renderPipeline = this._renderPipelines[renderPipelineName];
  79926. if (!renderPipeline) {
  79927. return;
  79928. }
  79929. renderPipeline._attachCameras(cameras, unique);
  79930. };
  79931. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79932. var renderPipeline = this._renderPipelines[renderPipelineName];
  79933. if (!renderPipeline) {
  79934. return;
  79935. }
  79936. renderPipeline._detachCameras(cameras);
  79937. };
  79938. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79939. var renderPipeline = this._renderPipelines[renderPipelineName];
  79940. if (!renderPipeline) {
  79941. return;
  79942. }
  79943. renderPipeline._enableEffect(renderEffectName, cameras);
  79944. };
  79945. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79946. var renderPipeline = this._renderPipelines[renderPipelineName];
  79947. if (!renderPipeline) {
  79948. return;
  79949. }
  79950. renderPipeline._disableEffect(renderEffectName, cameras);
  79951. };
  79952. PostProcessRenderPipelineManager.prototype.update = function () {
  79953. for (var renderPipelineName in this._renderPipelines) {
  79954. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79955. var pipeline = this._renderPipelines[renderPipelineName];
  79956. if (!pipeline.isSupported) {
  79957. pipeline.dispose();
  79958. delete this._renderPipelines[renderPipelineName];
  79959. }
  79960. else {
  79961. pipeline._update();
  79962. }
  79963. }
  79964. }
  79965. };
  79966. /** @hidden */
  79967. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79968. for (var renderPipelineName in this._renderPipelines) {
  79969. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79970. var pipeline = this._renderPipelines[renderPipelineName];
  79971. pipeline._rebuild();
  79972. }
  79973. }
  79974. };
  79975. PostProcessRenderPipelineManager.prototype.dispose = function () {
  79976. for (var renderPipelineName in this._renderPipelines) {
  79977. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79978. var pipeline = this._renderPipelines[renderPipelineName];
  79979. pipeline.dispose();
  79980. }
  79981. }
  79982. };
  79983. return PostProcessRenderPipelineManager;
  79984. }());
  79985. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  79986. })(BABYLON || (BABYLON = {}));
  79987. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  79988. var BABYLON;
  79989. (function (BABYLON) {
  79990. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  79991. get: function () {
  79992. if (!this._postProcessRenderPipelineManager) {
  79993. // Register the G Buffer component to the scene.
  79994. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  79995. if (!component) {
  79996. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  79997. this._addComponent(component);
  79998. }
  79999. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  80000. }
  80001. return this._postProcessRenderPipelineManager;
  80002. },
  80003. enumerable: true,
  80004. configurable: true
  80005. });
  80006. /**
  80007. * Defines the Render Pipeline scene component responsible to rendering pipelines
  80008. */
  80009. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  80010. /**
  80011. * Creates a new instance of the component for the given scene
  80012. * @param scene Defines the scene to register the component in
  80013. */
  80014. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  80015. /**
  80016. * The component name helpfull to identify the component in the list of scene components.
  80017. */
  80018. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  80019. this.scene = scene;
  80020. }
  80021. /**
  80022. * Registers the component in a given scene
  80023. */
  80024. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  80025. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  80026. };
  80027. /**
  80028. * Rebuilds the elements related to this component in case of
  80029. * context lost for instance.
  80030. */
  80031. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  80032. if (this.scene._postProcessRenderPipelineManager) {
  80033. this.scene._postProcessRenderPipelineManager._rebuild();
  80034. }
  80035. };
  80036. /**
  80037. * Disposes the component and the associated ressources
  80038. */
  80039. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  80040. if (this.scene._postProcessRenderPipelineManager) {
  80041. this.scene._postProcessRenderPipelineManager.dispose();
  80042. }
  80043. };
  80044. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80045. if (this.scene._postProcessRenderPipelineManager) {
  80046. this.scene._postProcessRenderPipelineManager.update();
  80047. }
  80048. };
  80049. return PostProcessRenderPipelineManagerSceneComponent;
  80050. }());
  80051. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  80052. })(BABYLON || (BABYLON = {}));
  80053. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  80054. var BABYLON;
  80055. (function (BABYLON) {
  80056. /**
  80057. * This represents a set of one or more post processes in Babylon.
  80058. * A post process can be used to apply a shader to a texture after it is rendered.
  80059. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  80060. */
  80061. var PostProcessRenderEffect = /** @class */ (function () {
  80062. /**
  80063. * Instantiates a post process render effect.
  80064. * A post process can be used to apply a shader to a texture after it is rendered.
  80065. * @param engine The engine the effect is tied to
  80066. * @param name The name of the effect
  80067. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  80068. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  80069. */
  80070. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  80071. this._name = name;
  80072. this._singleInstance = singleInstance || true;
  80073. this._getPostProcesses = getPostProcesses;
  80074. this._cameras = {};
  80075. this._indicesForCamera = {};
  80076. this._postProcesses = {};
  80077. }
  80078. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  80079. /**
  80080. * Checks if all the post processes in the effect are supported.
  80081. */
  80082. get: function () {
  80083. for (var index in this._postProcesses) {
  80084. if (this._postProcesses.hasOwnProperty(index)) {
  80085. var pps = this._postProcesses[index];
  80086. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  80087. if (!pps[ppIndex].isSupported) {
  80088. return false;
  80089. }
  80090. }
  80091. }
  80092. }
  80093. return true;
  80094. },
  80095. enumerable: true,
  80096. configurable: true
  80097. });
  80098. /**
  80099. * Updates the current state of the effect
  80100. * @hidden
  80101. */
  80102. PostProcessRenderEffect.prototype._update = function () {
  80103. };
  80104. /**
  80105. * Attaches the effect on cameras
  80106. * @param cameras The camera to attach to.
  80107. * @hidden
  80108. */
  80109. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  80110. var _this = this;
  80111. var cameraKey;
  80112. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80113. if (!cams) {
  80114. return;
  80115. }
  80116. for (var i = 0; i < cams.length; i++) {
  80117. var camera = cams[i];
  80118. var cameraName = camera.name;
  80119. if (this._singleInstance) {
  80120. cameraKey = 0;
  80121. }
  80122. else {
  80123. cameraKey = cameraName;
  80124. }
  80125. if (!this._postProcesses[cameraKey]) {
  80126. var postProcess = this._getPostProcesses();
  80127. if (postProcess) {
  80128. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  80129. }
  80130. }
  80131. if (!this._indicesForCamera[cameraName]) {
  80132. this._indicesForCamera[cameraName] = [];
  80133. }
  80134. this._postProcesses[cameraKey].forEach(function (postProcess) {
  80135. var index = camera.attachPostProcess(postProcess);
  80136. _this._indicesForCamera[cameraName].push(index);
  80137. });
  80138. if (!this._cameras[cameraName]) {
  80139. this._cameras[cameraName] = camera;
  80140. }
  80141. }
  80142. };
  80143. /**
  80144. * Detatches the effect on cameras
  80145. * @param cameras The camera to detatch from.
  80146. * @hidden
  80147. */
  80148. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  80149. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80150. if (!cams) {
  80151. return;
  80152. }
  80153. for (var i = 0; i < cams.length; i++) {
  80154. var camera = cams[i];
  80155. var cameraName = camera.name;
  80156. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80157. camera.detachPostProcess(postProcess);
  80158. });
  80159. if (this._cameras[cameraName]) {
  80160. //this._indicesForCamera.splice(index, 1);
  80161. this._cameras[cameraName] = null;
  80162. }
  80163. }
  80164. };
  80165. /**
  80166. * Enables the effect on given cameras
  80167. * @param cameras The camera to enable.
  80168. * @hidden
  80169. */
  80170. PostProcessRenderEffect.prototype._enable = function (cameras) {
  80171. var _this = this;
  80172. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80173. if (!cams) {
  80174. return;
  80175. }
  80176. for (var i = 0; i < cams.length; i++) {
  80177. var camera = cams[i];
  80178. var cameraName = camera.name;
  80179. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  80180. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  80181. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80182. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  80183. });
  80184. }
  80185. }
  80186. }
  80187. };
  80188. /**
  80189. * Disables the effect on the given cameras
  80190. * @param cameras The camera to disable.
  80191. * @hidden
  80192. */
  80193. PostProcessRenderEffect.prototype._disable = function (cameras) {
  80194. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80195. if (!cams) {
  80196. return;
  80197. }
  80198. for (var i = 0; i < cams.length; i++) {
  80199. var camera = cams[i];
  80200. var cameraName = camera.name;
  80201. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80202. camera.detachPostProcess(postProcess);
  80203. });
  80204. }
  80205. };
  80206. /**
  80207. * Gets a list of the post processes contained in the effect.
  80208. * @param camera The camera to get the post processes on.
  80209. * @returns The list of the post processes in the effect.
  80210. */
  80211. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  80212. if (this._singleInstance) {
  80213. return this._postProcesses[0];
  80214. }
  80215. else {
  80216. if (!camera) {
  80217. return null;
  80218. }
  80219. return this._postProcesses[camera.name];
  80220. }
  80221. };
  80222. return PostProcessRenderEffect;
  80223. }());
  80224. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  80225. })(BABYLON || (BABYLON = {}));
  80226. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  80227. var BABYLON;
  80228. (function (BABYLON) {
  80229. var PostProcessRenderPipeline = /** @class */ (function () {
  80230. function PostProcessRenderPipeline(engine, name) {
  80231. this.engine = engine;
  80232. this._name = name;
  80233. this._renderEffects = {};
  80234. this._renderEffectsForIsolatedPass = new Array();
  80235. this._cameras = [];
  80236. }
  80237. PostProcessRenderPipeline.prototype.getClassName = function () {
  80238. return "PostProcessRenderPipeline";
  80239. };
  80240. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  80241. get: function () {
  80242. for (var renderEffectName in this._renderEffects) {
  80243. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80244. if (!this._renderEffects[renderEffectName].isSupported) {
  80245. return false;
  80246. }
  80247. }
  80248. }
  80249. return true;
  80250. },
  80251. enumerable: true,
  80252. configurable: true
  80253. });
  80254. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  80255. this._renderEffects[renderEffect._name] = renderEffect;
  80256. };
  80257. // private
  80258. /** @hidden */
  80259. PostProcessRenderPipeline.prototype._rebuild = function () {
  80260. };
  80261. /** @hidden */
  80262. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  80263. var renderEffects = this._renderEffects[renderEffectName];
  80264. if (!renderEffects) {
  80265. return;
  80266. }
  80267. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80268. };
  80269. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  80270. var renderEffects = this._renderEffects[renderEffectName];
  80271. if (!renderEffects) {
  80272. return;
  80273. }
  80274. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80275. };
  80276. /** @hidden */
  80277. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  80278. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80279. if (!cams) {
  80280. return;
  80281. }
  80282. var indicesToDelete = [];
  80283. var i;
  80284. for (i = 0; i < cams.length; i++) {
  80285. var camera = cams[i];
  80286. var cameraName = camera.name;
  80287. if (this._cameras.indexOf(camera) === -1) {
  80288. this._cameras[cameraName] = camera;
  80289. }
  80290. else if (unique) {
  80291. indicesToDelete.push(i);
  80292. }
  80293. }
  80294. for (i = 0; i < indicesToDelete.length; i++) {
  80295. cameras.splice(indicesToDelete[i], 1);
  80296. }
  80297. for (var renderEffectName in this._renderEffects) {
  80298. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80299. this._renderEffects[renderEffectName]._attachCameras(cams);
  80300. }
  80301. }
  80302. };
  80303. /** @hidden */
  80304. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  80305. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80306. if (!cams) {
  80307. return;
  80308. }
  80309. for (var renderEffectName in this._renderEffects) {
  80310. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80311. this._renderEffects[renderEffectName]._detachCameras(cams);
  80312. }
  80313. }
  80314. for (var i = 0; i < cams.length; i++) {
  80315. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  80316. }
  80317. };
  80318. /** @hidden */
  80319. PostProcessRenderPipeline.prototype._update = function () {
  80320. for (var renderEffectName in this._renderEffects) {
  80321. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80322. this._renderEffects[renderEffectName]._update();
  80323. }
  80324. }
  80325. for (var i = 0; i < this._cameras.length; i++) {
  80326. var cameraName = this._cameras[i].name;
  80327. if (this._renderEffectsForIsolatedPass[cameraName]) {
  80328. this._renderEffectsForIsolatedPass[cameraName]._update();
  80329. }
  80330. }
  80331. };
  80332. /** @hidden */
  80333. PostProcessRenderPipeline.prototype._reset = function () {
  80334. this._renderEffects = {};
  80335. this._renderEffectsForIsolatedPass = new Array();
  80336. };
  80337. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  80338. // 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)
  80339. var effectKeys = Object.keys(this._renderEffects);
  80340. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  80341. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  80342. if (postProcesses) {
  80343. postProcesses[0].samples = sampleCount;
  80344. return true;
  80345. }
  80346. }
  80347. return false;
  80348. };
  80349. PostProcessRenderPipeline.prototype.dispose = function () {
  80350. // Must be implemented by children
  80351. };
  80352. __decorate([
  80353. BABYLON.serialize()
  80354. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  80355. return PostProcessRenderPipeline;
  80356. }());
  80357. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  80358. })(BABYLON || (BABYLON = {}));
  80359. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  80360. var BABYLON;
  80361. (function (BABYLON) {
  80362. /**
  80363. * This represents a depth renderer in Babylon.
  80364. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  80365. */
  80366. var DepthRenderer = /** @class */ (function () {
  80367. /**
  80368. * Instantiates a depth renderer
  80369. * @param scene The scene the renderer belongs to
  80370. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  80371. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  80372. */
  80373. function DepthRenderer(scene, type, camera) {
  80374. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  80375. if (camera === void 0) { camera = null; }
  80376. var _this = this;
  80377. /**
  80378. * Specifiess that the depth renderer will only be used within
  80379. * the camera it is created for.
  80380. * This can help forcing its rendering during the camera processing.
  80381. */
  80382. this.useOnlyInActiveCamera = false;
  80383. this._scene = scene;
  80384. // Register the G Buffer component to the scene.
  80385. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  80386. if (!component) {
  80387. component = new BABYLON.DepthRendererSceneComponent(scene);
  80388. scene._addComponent(component);
  80389. }
  80390. this._camera = camera;
  80391. var engine = scene.getEngine();
  80392. // Render target
  80393. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  80394. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80395. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80396. this._depthMap.refreshRate = 1;
  80397. this._depthMap.renderParticles = false;
  80398. this._depthMap.renderList = null;
  80399. // Camera to get depth map from to support multiple concurrent cameras
  80400. this._depthMap.activeCamera = this._camera;
  80401. this._depthMap.ignoreCameraViewport = true;
  80402. this._depthMap.useCameraPostProcesses = false;
  80403. // set default depth value to 1.0 (far away)
  80404. this._depthMap.onClearObservable.add(function (engine) {
  80405. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  80406. });
  80407. // Custom render function
  80408. var renderSubMesh = function (subMesh) {
  80409. var mesh = subMesh.getRenderingMesh();
  80410. var scene = _this._scene;
  80411. var engine = scene.getEngine();
  80412. var material = subMesh.getMaterial();
  80413. if (!material) {
  80414. return;
  80415. }
  80416. // Culling and reverse (right handed system)
  80417. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80418. // Managing instances
  80419. var batch = mesh._getInstancesRenderList(subMesh._id);
  80420. if (batch.mustReturn) {
  80421. return;
  80422. }
  80423. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80424. var camera = _this._camera || scene.activeCamera;
  80425. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  80426. engine.enableEffect(_this._effect);
  80427. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80428. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80429. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  80430. // Alpha test
  80431. if (material && material.needAlphaTesting()) {
  80432. var alphaTexture = material.getAlphaTestTexture();
  80433. if (alphaTexture) {
  80434. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80435. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80436. }
  80437. }
  80438. // Bones
  80439. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80440. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80441. }
  80442. // Draw
  80443. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80444. }
  80445. };
  80446. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80447. var index;
  80448. if (depthOnlySubMeshes.length) {
  80449. engine.setColorWrite(false);
  80450. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80451. renderSubMesh(depthOnlySubMeshes.data[index]);
  80452. }
  80453. engine.setColorWrite(true);
  80454. }
  80455. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80456. renderSubMesh(opaqueSubMeshes.data[index]);
  80457. }
  80458. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80459. renderSubMesh(alphaTestSubMeshes.data[index]);
  80460. }
  80461. };
  80462. }
  80463. /**
  80464. * Creates the depth rendering effect and checks if the effect is ready.
  80465. * @param subMesh The submesh to be used to render the depth map of
  80466. * @param useInstances If multiple world instances should be used
  80467. * @returns if the depth renderer is ready to render the depth map
  80468. */
  80469. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  80470. var material = subMesh.getMaterial();
  80471. if (material.disableDepthWrite) {
  80472. return false;
  80473. }
  80474. var defines = [];
  80475. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80476. var mesh = subMesh.getMesh();
  80477. // Alpha test
  80478. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  80479. defines.push("#define ALPHATEST");
  80480. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80481. attribs.push(BABYLON.VertexBuffer.UVKind);
  80482. defines.push("#define UV1");
  80483. }
  80484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80485. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80486. defines.push("#define UV2");
  80487. }
  80488. }
  80489. // Bones
  80490. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80491. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80492. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80493. if (mesh.numBoneInfluencers > 4) {
  80494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80496. }
  80497. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80498. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80499. }
  80500. else {
  80501. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80502. }
  80503. // Instances
  80504. if (useInstances) {
  80505. defines.push("#define INSTANCES");
  80506. attribs.push("world0");
  80507. attribs.push("world1");
  80508. attribs.push("world2");
  80509. attribs.push("world3");
  80510. }
  80511. // Get correct effect
  80512. var join = defines.join("\n");
  80513. if (this._cachedDefines !== join) {
  80514. this._cachedDefines = join;
  80515. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80516. }
  80517. return this._effect.isReady();
  80518. };
  80519. /**
  80520. * Gets the texture which the depth map will be written to.
  80521. * @returns The depth map texture
  80522. */
  80523. DepthRenderer.prototype.getDepthMap = function () {
  80524. return this._depthMap;
  80525. };
  80526. /**
  80527. * Disposes of the depth renderer.
  80528. */
  80529. DepthRenderer.prototype.dispose = function () {
  80530. this._depthMap.dispose();
  80531. };
  80532. return DepthRenderer;
  80533. }());
  80534. BABYLON.DepthRenderer = DepthRenderer;
  80535. })(BABYLON || (BABYLON = {}));
  80536. //# sourceMappingURL=babylon.depthRenderer.js.map
  80537. var BABYLON;
  80538. (function (BABYLON) {
  80539. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80540. camera = camera || this.activeCamera;
  80541. if (!camera) {
  80542. throw "No camera available to enable depth renderer";
  80543. }
  80544. if (!this._depthRenderer) {
  80545. this._depthRenderer = {};
  80546. }
  80547. if (!this._depthRenderer[camera.id]) {
  80548. var textureType = 0;
  80549. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80550. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80551. }
  80552. else if (this.getEngine().getCaps().textureFloatRender) {
  80553. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80554. }
  80555. else {
  80556. throw "Depth renderer does not support int texture type";
  80557. }
  80558. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80559. }
  80560. return this._depthRenderer[camera.id];
  80561. };
  80562. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80563. camera = camera || this.activeCamera;
  80564. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80565. return;
  80566. }
  80567. this._depthRenderer[camera.id].dispose();
  80568. delete this._depthRenderer[camera.id];
  80569. };
  80570. /**
  80571. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80572. * in several rendering techniques.
  80573. */
  80574. var DepthRendererSceneComponent = /** @class */ (function () {
  80575. /**
  80576. * Creates a new instance of the component for the given scene
  80577. * @param scene Defines the scene to register the component in
  80578. */
  80579. function DepthRendererSceneComponent(scene) {
  80580. /**
  80581. * The component name helpfull to identify the component in the list of scene components.
  80582. */
  80583. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80584. this.scene = scene;
  80585. }
  80586. /**
  80587. * Registers the component in a given scene
  80588. */
  80589. DepthRendererSceneComponent.prototype.register = function () {
  80590. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80591. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80592. };
  80593. /**
  80594. * Rebuilds the elements related to this component in case of
  80595. * context lost for instance.
  80596. */
  80597. DepthRendererSceneComponent.prototype.rebuild = function () {
  80598. // Nothing to do for this component
  80599. };
  80600. /**
  80601. * Disposes the component and the associated ressources
  80602. */
  80603. DepthRendererSceneComponent.prototype.dispose = function () {
  80604. for (var key in this.scene._depthRenderer) {
  80605. this.scene._depthRenderer[key].dispose();
  80606. }
  80607. };
  80608. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80609. if (this.scene._depthRenderer) {
  80610. for (var key in this.scene._depthRenderer) {
  80611. var depthRenderer = this.scene._depthRenderer[key];
  80612. if (!depthRenderer.useOnlyInActiveCamera) {
  80613. renderTargets.push(depthRenderer.getDepthMap());
  80614. }
  80615. }
  80616. }
  80617. };
  80618. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80619. if (this.scene._depthRenderer) {
  80620. for (var key in this.scene._depthRenderer) {
  80621. var depthRenderer = this.scene._depthRenderer[key];
  80622. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80623. renderTargets.push(depthRenderer.getDepthMap());
  80624. }
  80625. }
  80626. }
  80627. };
  80628. return DepthRendererSceneComponent;
  80629. }());
  80630. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80631. })(BABYLON || (BABYLON = {}));
  80632. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80633. var BABYLON;
  80634. (function (BABYLON) {
  80635. /**
  80636. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80637. */
  80638. var GeometryBufferRenderer = /** @class */ (function () {
  80639. /**
  80640. * Creates a new G Buffer for the scene
  80641. * @param scene The scene the buffer belongs to
  80642. * @param ratio How big is the buffer related to the main canvas.
  80643. */
  80644. function GeometryBufferRenderer(scene, ratio) {
  80645. if (ratio === void 0) { ratio = 1; }
  80646. this._enablePosition = false;
  80647. this._scene = scene;
  80648. this._ratio = ratio;
  80649. // Register the G Buffer component to the scene.
  80650. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  80651. if (!component) {
  80652. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  80653. scene._addComponent(component);
  80654. }
  80655. // Render target
  80656. this._createRenderTargets();
  80657. }
  80658. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  80659. /**
  80660. * Set the render list (meshes to be rendered) used in the G buffer.
  80661. */
  80662. set: function (meshes) {
  80663. this._multiRenderTarget.renderList = meshes;
  80664. },
  80665. enumerable: true,
  80666. configurable: true
  80667. });
  80668. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  80669. /**
  80670. * Gets wether or not G buffer are supported by the running hardware.
  80671. * This requires draw buffer supports
  80672. */
  80673. get: function () {
  80674. return this._multiRenderTarget.isSupported;
  80675. },
  80676. enumerable: true,
  80677. configurable: true
  80678. });
  80679. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  80680. /**
  80681. * Gets wether or not position are enabled for the G buffer.
  80682. */
  80683. get: function () {
  80684. return this._enablePosition;
  80685. },
  80686. /**
  80687. * Sets wether or not position are enabled for the G buffer.
  80688. */
  80689. set: function (enable) {
  80690. this._enablePosition = enable;
  80691. this.dispose();
  80692. this._createRenderTargets();
  80693. },
  80694. enumerable: true,
  80695. configurable: true
  80696. });
  80697. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  80698. /**
  80699. * Gets the scene associated with the buffer.
  80700. */
  80701. get: function () {
  80702. return this._scene;
  80703. },
  80704. enumerable: true,
  80705. configurable: true
  80706. });
  80707. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  80708. /**
  80709. * Gets the ratio used by the buffer during its creation.
  80710. * How big is the buffer related to the main canvas.
  80711. */
  80712. get: function () {
  80713. return this._ratio;
  80714. },
  80715. enumerable: true,
  80716. configurable: true
  80717. });
  80718. /**
  80719. * Checks wether everything is ready to render a submesh to the G buffer.
  80720. * @param subMesh the submesh to check readiness for
  80721. * @param useInstances is the mesh drawn using instance or not
  80722. * @returns true if ready otherwise false
  80723. */
  80724. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  80725. var material = subMesh.getMaterial();
  80726. if (material && material.disableDepthWrite) {
  80727. return false;
  80728. }
  80729. var defines = [];
  80730. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80731. var mesh = subMesh.getMesh();
  80732. // Alpha test
  80733. if (material && material.needAlphaTesting()) {
  80734. defines.push("#define ALPHATEST");
  80735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80736. attribs.push(BABYLON.VertexBuffer.UVKind);
  80737. defines.push("#define UV1");
  80738. }
  80739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80740. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80741. defines.push("#define UV2");
  80742. }
  80743. }
  80744. // Buffers
  80745. if (this._enablePosition) {
  80746. defines.push("#define POSITION");
  80747. }
  80748. // Bones
  80749. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80752. if (mesh.numBoneInfluencers > 4) {
  80753. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80754. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80755. }
  80756. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80757. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80758. }
  80759. else {
  80760. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80761. }
  80762. // Instances
  80763. if (useInstances) {
  80764. defines.push("#define INSTANCES");
  80765. attribs.push("world0");
  80766. attribs.push("world1");
  80767. attribs.push("world2");
  80768. attribs.push("world3");
  80769. }
  80770. // Get correct effect
  80771. var join = defines.join("\n");
  80772. if (this._cachedDefines !== join) {
  80773. this._cachedDefines = join;
  80774. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  80775. }
  80776. return this._effect.isReady();
  80777. };
  80778. /**
  80779. * Gets the current underlying G Buffer.
  80780. * @returns the buffer
  80781. */
  80782. GeometryBufferRenderer.prototype.getGBuffer = function () {
  80783. return this._multiRenderTarget;
  80784. };
  80785. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  80786. /**
  80787. * Gets the number of samples used to render the buffer (anti aliasing).
  80788. */
  80789. get: function () {
  80790. return this._multiRenderTarget.samples;
  80791. },
  80792. /**
  80793. * Sets the number of samples used to render the buffer (anti aliasing).
  80794. */
  80795. set: function (value) {
  80796. this._multiRenderTarget.samples = value;
  80797. },
  80798. enumerable: true,
  80799. configurable: true
  80800. });
  80801. /**
  80802. * Disposes the renderer and frees up associated resources.
  80803. */
  80804. GeometryBufferRenderer.prototype.dispose = function () {
  80805. this.getGBuffer().dispose();
  80806. };
  80807. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  80808. var _this = this;
  80809. var engine = this._scene.getEngine();
  80810. var count = this._enablePosition ? 3 : 2;
  80811. 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 });
  80812. if (!this.isSupported) {
  80813. return;
  80814. }
  80815. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80816. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80817. this._multiRenderTarget.refreshRate = 1;
  80818. this._multiRenderTarget.renderParticles = false;
  80819. this._multiRenderTarget.renderList = null;
  80820. // set default depth value to 1.0 (far away)
  80821. this._multiRenderTarget.onClearObservable.add(function (engine) {
  80822. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  80823. });
  80824. // Custom render function
  80825. var renderSubMesh = function (subMesh) {
  80826. var mesh = subMesh.getRenderingMesh();
  80827. var scene = _this._scene;
  80828. var engine = scene.getEngine();
  80829. var material = subMesh.getMaterial();
  80830. if (!material) {
  80831. return;
  80832. }
  80833. // Culling
  80834. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80835. // Managing instances
  80836. var batch = mesh._getInstancesRenderList(subMesh._id);
  80837. if (batch.mustReturn) {
  80838. return;
  80839. }
  80840. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80841. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  80842. engine.enableEffect(_this._effect);
  80843. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80844. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80845. _this._effect.setMatrix("view", scene.getViewMatrix());
  80846. // Alpha test
  80847. if (material && material.needAlphaTesting()) {
  80848. var alphaTexture = material.getAlphaTestTexture();
  80849. if (alphaTexture) {
  80850. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80851. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80852. }
  80853. }
  80854. // Bones
  80855. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80856. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80857. }
  80858. // Draw
  80859. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80860. }
  80861. };
  80862. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80863. var index;
  80864. if (depthOnlySubMeshes.length) {
  80865. engine.setColorWrite(false);
  80866. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80867. renderSubMesh(depthOnlySubMeshes.data[index]);
  80868. }
  80869. engine.setColorWrite(true);
  80870. }
  80871. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80872. renderSubMesh(opaqueSubMeshes.data[index]);
  80873. }
  80874. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80875. renderSubMesh(alphaTestSubMeshes.data[index]);
  80876. }
  80877. };
  80878. };
  80879. return GeometryBufferRenderer;
  80880. }());
  80881. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80882. })(BABYLON || (BABYLON = {}));
  80883. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80884. var BABYLON;
  80885. (function (BABYLON) {
  80886. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80887. get: function () {
  80888. this._geometryBufferRenderer;
  80889. },
  80890. set: function (value) {
  80891. if (value && value.isSupported) {
  80892. this._geometryBufferRenderer = value;
  80893. }
  80894. ;
  80895. },
  80896. enumerable: true,
  80897. configurable: true
  80898. });
  80899. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80900. if (ratio === void 0) { ratio = 1; }
  80901. if (this._geometryBufferRenderer) {
  80902. return this._geometryBufferRenderer;
  80903. }
  80904. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80905. if (!this._geometryBufferRenderer.isSupported) {
  80906. this._geometryBufferRenderer = null;
  80907. }
  80908. return this._geometryBufferRenderer;
  80909. };
  80910. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80911. if (!this._geometryBufferRenderer) {
  80912. return;
  80913. }
  80914. this._geometryBufferRenderer.dispose();
  80915. this._geometryBufferRenderer = null;
  80916. };
  80917. /**
  80918. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80919. * in several rendering techniques.
  80920. */
  80921. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80922. /**
  80923. * Creates a new instance of the component for the given scene
  80924. * @param scene Defines the scene to register the component in
  80925. */
  80926. function GeometryBufferRendererSceneComponent(scene) {
  80927. /**
  80928. * The component name helpful to identify the component in the list of scene components.
  80929. */
  80930. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80931. this.scene = scene;
  80932. }
  80933. /**
  80934. * Registers the component in a given scene
  80935. */
  80936. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80937. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80938. };
  80939. /**
  80940. * Rebuilds the elements related to this component in case of
  80941. * context lost for instance.
  80942. */
  80943. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80944. // Nothing to do for this component
  80945. };
  80946. /**
  80947. * Disposes the component and the associated ressources
  80948. */
  80949. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80950. // Nothing to do for this component
  80951. };
  80952. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80953. if (this.scene._geometryBufferRenderer) {
  80954. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80955. }
  80956. };
  80957. return GeometryBufferRendererSceneComponent;
  80958. }());
  80959. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80960. })(BABYLON || (BABYLON = {}));
  80961. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80962. var BABYLON;
  80963. (function (BABYLON) {
  80964. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80965. __extends(SSAORenderingPipeline, _super);
  80966. /**
  80967. * @constructor
  80968. * @param {string} name - The rendering pipeline name
  80969. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80970. * @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 }
  80971. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80972. */
  80973. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  80974. var _this = _super.call(this, scene.getEngine(), name) || this;
  80975. // Members
  80976. /**
  80977. * The PassPostProcess id in the pipeline that contains the original scene color
  80978. */
  80979. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80980. /**
  80981. * The SSAO PostProcess id in the pipeline
  80982. */
  80983. _this.SSAORenderEffect = "SSAORenderEffect";
  80984. /**
  80985. * The horizontal blur PostProcess id in the pipeline
  80986. */
  80987. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80988. /**
  80989. * The vertical blur PostProcess id in the pipeline
  80990. */
  80991. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80992. /**
  80993. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80994. */
  80995. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80996. /**
  80997. * The output strength of the SSAO post-process. Default value is 1.0.
  80998. */
  80999. _this.totalStrength = 1.0;
  81000. /**
  81001. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  81002. */
  81003. _this.radius = 0.0001;
  81004. /**
  81005. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  81006. * Must not be equal to fallOff and superior to fallOff.
  81007. * Default value is 0.975
  81008. */
  81009. _this.area = 0.0075;
  81010. /**
  81011. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  81012. * Must not be equal to area and inferior to area.
  81013. * Default value is 0.0
  81014. */
  81015. _this.fallOff = 0.000001;
  81016. /**
  81017. * The base color of the SSAO post-process
  81018. * The final result is "base + ssao" between [0, 1]
  81019. */
  81020. _this.base = 0.5;
  81021. _this._firstUpdate = true;
  81022. _this._scene = scene;
  81023. // Set up assets
  81024. _this._createRandomTexture();
  81025. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81026. var ssaoRatio = ratio.ssaoRatio || ratio;
  81027. var combineRatio = ratio.combineRatio || ratio;
  81028. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81029. _this._createSSAOPostProcess(ssaoRatio);
  81030. _this._createBlurPostProcess(ssaoRatio);
  81031. _this._createSSAOCombinePostProcess(combineRatio);
  81032. // Set up pipeline
  81033. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81034. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81035. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81036. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81037. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81038. // Finish
  81039. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81040. if (cameras)
  81041. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81042. return _this;
  81043. }
  81044. // Public Methods
  81045. /**
  81046. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81047. */
  81048. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81049. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81050. for (var i = 0; i < this._scene.cameras.length; i++) {
  81051. var camera = this._scene.cameras[i];
  81052. this._originalColorPostProcess.dispose(camera);
  81053. this._ssaoPostProcess.dispose(camera);
  81054. this._blurHPostProcess.dispose(camera);
  81055. this._blurVPostProcess.dispose(camera);
  81056. this._ssaoCombinePostProcess.dispose(camera);
  81057. }
  81058. this._randomTexture.dispose();
  81059. if (disableDepthRender)
  81060. this._scene.disableDepthRenderer();
  81061. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81062. _super.prototype.dispose.call(this);
  81063. };
  81064. // Private Methods
  81065. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  81066. var _this = this;
  81067. var size = 16;
  81068. 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);
  81069. 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);
  81070. this._blurHPostProcess.onActivateObservable.add(function () {
  81071. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  81072. _this._blurHPostProcess.kernel = size * dw;
  81073. });
  81074. this._blurVPostProcess.onActivateObservable.add(function () {
  81075. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  81076. _this._blurVPostProcess.kernel = size * dw;
  81077. });
  81078. };
  81079. /** @hidden */
  81080. SSAORenderingPipeline.prototype._rebuild = function () {
  81081. this._firstUpdate = true;
  81082. _super.prototype._rebuild.call(this);
  81083. };
  81084. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81085. var _this = this;
  81086. var numSamples = 16;
  81087. var sampleSphere = [
  81088. 0.5381, 0.1856, -0.4319,
  81089. 0.1379, 0.2486, 0.4430,
  81090. 0.3371, 0.5679, -0.0057,
  81091. -0.6999, -0.0451, -0.0019,
  81092. 0.0689, -0.1598, -0.8547,
  81093. 0.0560, 0.0069, -0.1843,
  81094. -0.0146, 0.1402, 0.0762,
  81095. 0.0100, -0.1924, -0.0344,
  81096. -0.3577, -0.5301, -0.4358,
  81097. -0.3169, 0.1063, 0.0158,
  81098. 0.0103, -0.5869, 0.0046,
  81099. -0.0897, -0.4940, 0.3287,
  81100. 0.7119, -0.0154, -0.0918,
  81101. -0.0533, 0.0596, -0.5411,
  81102. 0.0352, -0.0631, 0.5460,
  81103. -0.4776, 0.2847, -0.0271
  81104. ];
  81105. var samplesFactor = 1.0 / numSamples;
  81106. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  81107. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81108. "area", "fallOff", "base", "range", "viewport"
  81109. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81110. this._ssaoPostProcess.onApply = function (effect) {
  81111. if (_this._firstUpdate) {
  81112. effect.setArray3("sampleSphere", sampleSphere);
  81113. effect.setFloat("samplesFactor", samplesFactor);
  81114. effect.setFloat("randTextureTiles", 4.0);
  81115. }
  81116. effect.setFloat("totalStrength", _this.totalStrength);
  81117. effect.setFloat("radius", _this.radius);
  81118. effect.setFloat("area", _this.area);
  81119. effect.setFloat("fallOff", _this.fallOff);
  81120. effect.setFloat("base", _this.base);
  81121. effect.setTexture("textureSampler", _this._depthTexture);
  81122. effect.setTexture("randomSampler", _this._randomTexture);
  81123. };
  81124. };
  81125. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81126. var _this = this;
  81127. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81128. this._ssaoCombinePostProcess.onApply = function (effect) {
  81129. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  81130. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81131. };
  81132. };
  81133. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  81134. var size = 512;
  81135. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81136. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81137. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81138. var context = this._randomTexture.getContext();
  81139. var rand = function (min, max) {
  81140. return Math.random() * (max - min) + min;
  81141. };
  81142. var randVector = BABYLON.Vector3.Zero();
  81143. for (var x = 0; x < size; x++) {
  81144. for (var y = 0; y < size; y++) {
  81145. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  81146. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  81147. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  81148. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81149. context.fillRect(x, y, 1, 1);
  81150. }
  81151. }
  81152. this._randomTexture.update(false);
  81153. };
  81154. __decorate([
  81155. BABYLON.serialize()
  81156. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  81157. __decorate([
  81158. BABYLON.serialize()
  81159. ], SSAORenderingPipeline.prototype, "radius", void 0);
  81160. __decorate([
  81161. BABYLON.serialize()
  81162. ], SSAORenderingPipeline.prototype, "area", void 0);
  81163. __decorate([
  81164. BABYLON.serialize()
  81165. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  81166. __decorate([
  81167. BABYLON.serialize()
  81168. ], SSAORenderingPipeline.prototype, "base", void 0);
  81169. return SSAORenderingPipeline;
  81170. }(BABYLON.PostProcessRenderPipeline));
  81171. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  81172. })(BABYLON || (BABYLON = {}));
  81173. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  81174. var BABYLON;
  81175. (function (BABYLON) {
  81176. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  81177. __extends(SSAO2RenderingPipeline, _super);
  81178. /**
  81179. * @constructor
  81180. * @param {string} name - The rendering pipeline name
  81181. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81182. * @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 }
  81183. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81184. */
  81185. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  81186. var _this = _super.call(this, scene.getEngine(), name) || this;
  81187. // Members
  81188. /**
  81189. * The PassPostProcess id in the pipeline that contains the original scene color
  81190. */
  81191. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81192. /**
  81193. * The SSAO PostProcess id in the pipeline
  81194. */
  81195. _this.SSAORenderEffect = "SSAORenderEffect";
  81196. /**
  81197. * The horizontal blur PostProcess id in the pipeline
  81198. */
  81199. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81200. /**
  81201. * The vertical blur PostProcess id in the pipeline
  81202. */
  81203. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81204. /**
  81205. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81206. */
  81207. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81208. /**
  81209. * The output strength of the SSAO post-process. Default value is 1.0.
  81210. */
  81211. _this.totalStrength = 1.0;
  81212. /**
  81213. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  81214. */
  81215. _this.maxZ = 100.0;
  81216. /**
  81217. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  81218. */
  81219. _this.minZAspect = 0.2;
  81220. _this._samples = 8;
  81221. _this._textureSamples = 1;
  81222. /**
  81223. * Are we using bilateral blur ?
  81224. */
  81225. _this._expensiveBlur = true;
  81226. /**
  81227. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  81228. */
  81229. _this.radius = 2.0;
  81230. /**
  81231. * The base color of the SSAO post-process
  81232. * The final result is "base + ssao" between [0, 1]
  81233. */
  81234. _this.base = 0;
  81235. _this._firstUpdate = true;
  81236. _this._bits = new Uint32Array(1);
  81237. _this._scene = scene;
  81238. _this._ratio = ratio;
  81239. if (!_this.isSupported) {
  81240. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  81241. return _this;
  81242. }
  81243. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  81244. var blurRatio = _this._ratio.blurRatio || ratio;
  81245. // Set up assets
  81246. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  81247. _this._createRandomTexture();
  81248. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  81249. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  81250. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81251. _this._originalColorPostProcess.samples = _this.textureSamples;
  81252. _this._createSSAOPostProcess(1.0);
  81253. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  81254. _this._createSSAOCombinePostProcess(blurRatio);
  81255. // Set up pipeline
  81256. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81257. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81258. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81259. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81261. // Finish
  81262. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81263. if (cameras)
  81264. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81265. return _this;
  81266. }
  81267. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  81268. get: function () {
  81269. return this._samples;
  81270. },
  81271. /**
  81272. * Number of samples used for the SSAO calculations. Default value is 8
  81273. */
  81274. set: function (n) {
  81275. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  81276. this._samples = n;
  81277. this._sampleSphere = this._generateHemisphere();
  81278. this._firstUpdate = true;
  81279. },
  81280. enumerable: true,
  81281. configurable: true
  81282. });
  81283. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  81284. get: function () {
  81285. return this._textureSamples;
  81286. },
  81287. /**
  81288. * Number of samples to use for antialiasing
  81289. */
  81290. set: function (n) {
  81291. this._textureSamples = n;
  81292. this._originalColorPostProcess.samples = n;
  81293. this._blurHPostProcess.samples = n;
  81294. this._blurVPostProcess.samples = n;
  81295. this._ssaoPostProcess.samples = n;
  81296. this._ssaoCombinePostProcess.samples = n;
  81297. },
  81298. enumerable: true,
  81299. configurable: true
  81300. });
  81301. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  81302. get: function () {
  81303. return this._expensiveBlur;
  81304. },
  81305. set: function (b) {
  81306. 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"]);
  81307. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  81308. this._expensiveBlur = b;
  81309. this._firstUpdate = true;
  81310. },
  81311. enumerable: true,
  81312. configurable: true
  81313. });
  81314. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  81315. /**
  81316. * Support test.
  81317. */
  81318. get: function () {
  81319. var engine = BABYLON.Engine.LastCreatedEngine;
  81320. if (!engine) {
  81321. return false;
  81322. }
  81323. return engine.getCaps().drawBuffersExtension;
  81324. },
  81325. enumerable: true,
  81326. configurable: true
  81327. });
  81328. // Public Methods
  81329. /**
  81330. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81331. */
  81332. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  81333. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  81334. for (var i = 0; i < this._scene.cameras.length; i++) {
  81335. var camera = this._scene.cameras[i];
  81336. this._originalColorPostProcess.dispose(camera);
  81337. this._ssaoPostProcess.dispose(camera);
  81338. this._blurHPostProcess.dispose(camera);
  81339. this._blurVPostProcess.dispose(camera);
  81340. this._ssaoCombinePostProcess.dispose(camera);
  81341. }
  81342. this._randomTexture.dispose();
  81343. if (disableGeometryBufferRenderer)
  81344. this._scene.disableGeometryBufferRenderer();
  81345. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81346. _super.prototype.dispose.call(this);
  81347. };
  81348. // Private Methods
  81349. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  81350. var _this = this;
  81351. this._samplerOffsets = [];
  81352. var expensive = this.expensiveBlur;
  81353. for (var i = -8; i < 8; i++) {
  81354. this._samplerOffsets.push(i * 2 + 0.5);
  81355. }
  81356. 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");
  81357. this._blurHPostProcess.onApply = function (effect) {
  81358. if (!_this._scene.activeCamera) {
  81359. return;
  81360. }
  81361. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  81362. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81363. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81364. effect.setFloat("radius", _this.radius);
  81365. effect.setTexture("depthSampler", _this._depthTexture);
  81366. if (_this._firstUpdate) {
  81367. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81368. }
  81369. };
  81370. 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");
  81371. this._blurVPostProcess.onApply = function (effect) {
  81372. if (!_this._scene.activeCamera) {
  81373. return;
  81374. }
  81375. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  81376. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81377. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81378. effect.setFloat("radius", _this.radius);
  81379. effect.setTexture("depthSampler", _this._depthTexture);
  81380. if (_this._firstUpdate) {
  81381. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81382. _this._firstUpdate = false;
  81383. }
  81384. };
  81385. this._blurHPostProcess.samples = this.textureSamples;
  81386. this._blurVPostProcess.samples = this.textureSamples;
  81387. };
  81388. /** @hidden */
  81389. SSAO2RenderingPipeline.prototype._rebuild = function () {
  81390. this._firstUpdate = true;
  81391. _super.prototype._rebuild.call(this);
  81392. };
  81393. //Van der Corput radical inverse
  81394. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  81395. this._bits[0] = i;
  81396. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  81397. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  81398. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  81399. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  81400. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  81401. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  81402. };
  81403. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  81404. return [i / n, this._radicalInverse_VdC(i)];
  81405. };
  81406. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  81407. var phi = v * 2.0 * Math.PI;
  81408. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  81409. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  81410. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  81411. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  81412. };
  81413. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  81414. var numSamples = this.samples;
  81415. var result = [];
  81416. var vector;
  81417. var i = 0;
  81418. while (i < numSamples) {
  81419. if (numSamples < 16) {
  81420. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  81421. }
  81422. else {
  81423. var rand = this._hammersley(i, numSamples);
  81424. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  81425. }
  81426. result.push(vector.x, vector.y, vector.z);
  81427. i++;
  81428. }
  81429. return result;
  81430. };
  81431. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81432. var _this = this;
  81433. var numSamples = this.samples;
  81434. this._sampleSphere = this._generateHemisphere();
  81435. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  81436. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81437. "base", "range", "projection", "near", "far", "texelSize",
  81438. "xViewport", "yViewport", "maxZ", "minZAspect"
  81439. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81440. this._ssaoPostProcess.onApply = function (effect) {
  81441. if (_this._firstUpdate) {
  81442. effect.setArray3("sampleSphere", _this._sampleSphere);
  81443. effect.setFloat("randTextureTiles", 32.0);
  81444. }
  81445. if (!_this._scene.activeCamera) {
  81446. return;
  81447. }
  81448. effect.setFloat("samplesFactor", 1 / _this.samples);
  81449. effect.setFloat("totalStrength", _this.totalStrength);
  81450. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  81451. effect.setFloat("radius", _this.radius);
  81452. effect.setFloat("maxZ", _this.maxZ);
  81453. effect.setFloat("minZAspect", _this.minZAspect);
  81454. effect.setFloat("base", _this.base);
  81455. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81456. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81457. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  81458. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  81459. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  81460. effect.setTexture("textureSampler", _this._depthTexture);
  81461. effect.setTexture("normalSampler", _this._normalTexture);
  81462. effect.setTexture("randomSampler", _this._randomTexture);
  81463. };
  81464. this._ssaoPostProcess.samples = this.textureSamples;
  81465. };
  81466. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81467. var _this = this;
  81468. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81469. this._ssaoCombinePostProcess.onApply = function (effect) {
  81470. var viewport = _this._scene.activeCamera.viewport;
  81471. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  81472. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81473. };
  81474. this._ssaoCombinePostProcess.samples = this.textureSamples;
  81475. };
  81476. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  81477. var size = 128;
  81478. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81479. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81480. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81481. var context = this._randomTexture.getContext();
  81482. var rand = function (min, max) {
  81483. return Math.random() * (max - min) + min;
  81484. };
  81485. var randVector = BABYLON.Vector3.Zero();
  81486. for (var x = 0; x < size; x++) {
  81487. for (var y = 0; y < size; y++) {
  81488. randVector.x = rand(0.0, 1.0);
  81489. randVector.y = rand(0.0, 1.0);
  81490. randVector.z = 0.0;
  81491. randVector.normalize();
  81492. randVector.scaleInPlace(255);
  81493. randVector.x = Math.floor(randVector.x);
  81494. randVector.y = Math.floor(randVector.y);
  81495. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81496. context.fillRect(x, y, 1, 1);
  81497. }
  81498. }
  81499. this._randomTexture.update(false);
  81500. };
  81501. /**
  81502. * Serialize the rendering pipeline (Used when exporting)
  81503. * @returns the serialized object
  81504. */
  81505. SSAO2RenderingPipeline.prototype.serialize = function () {
  81506. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81507. serializationObject.customType = "SSAO2RenderingPipeline";
  81508. return serializationObject;
  81509. };
  81510. /**
  81511. * Parse the serialized pipeline
  81512. * @param source Source pipeline.
  81513. * @param scene The scene to load the pipeline to.
  81514. * @param rootUrl The URL of the serialized pipeline.
  81515. * @returns An instantiated pipeline from the serialized object.
  81516. */
  81517. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81518. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81519. };
  81520. __decorate([
  81521. BABYLON.serialize()
  81522. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81523. __decorate([
  81524. BABYLON.serialize()
  81525. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81526. __decorate([
  81527. BABYLON.serialize()
  81528. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81529. __decorate([
  81530. BABYLON.serialize("samples")
  81531. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81532. __decorate([
  81533. BABYLON.serialize("textureSamples")
  81534. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81535. __decorate([
  81536. BABYLON.serialize()
  81537. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81538. __decorate([
  81539. BABYLON.serialize("expensiveBlur")
  81540. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81541. __decorate([
  81542. BABYLON.serialize()
  81543. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81544. __decorate([
  81545. BABYLON.serialize()
  81546. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81547. return SSAO2RenderingPipeline;
  81548. }(BABYLON.PostProcessRenderPipeline));
  81549. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81550. })(BABYLON || (BABYLON = {}));
  81551. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81552. // BABYLON.JS Chromatic Aberration GLSL Shader
  81553. // Author: Olivier Guyot
  81554. // Separates very slightly R, G and B colors on the edges of the screen
  81555. // Inspired by Francois Tarlier & Martins Upitis
  81556. var BABYLON;
  81557. (function (BABYLON) {
  81558. var LensRenderingPipeline = /** @class */ (function (_super) {
  81559. __extends(LensRenderingPipeline, _super);
  81560. /**
  81561. * @constructor
  81562. *
  81563. * Effect parameters are as follow:
  81564. * {
  81565. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81566. * edge_blur: number; // from 0 to x (1 for realism)
  81567. * distortion: number; // from 0 to x (1 for realism)
  81568. * grain_amount: number; // from 0 to 1
  81569. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81570. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81571. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81572. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81573. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81574. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81575. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81576. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81577. * }
  81578. * Note: if an effect parameter is unset, effect is disabled
  81579. *
  81580. * @param {string} name - The rendering pipeline name
  81581. * @param {object} parameters - An object containing all parameters (see above)
  81582. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81583. * @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)
  81584. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81585. */
  81586. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81587. if (ratio === void 0) { ratio = 1.0; }
  81588. var _this = _super.call(this, scene.getEngine(), name) || this;
  81589. // Lens effects can be of the following:
  81590. // - chromatic aberration (slight shift of RGB colors)
  81591. // - blur on the edge of the lens
  81592. // - lens distortion
  81593. // - depth-of-field blur & highlights enhancing
  81594. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81595. // - grain effect (noise or custom texture)
  81596. // Two additional texture samplers are needed:
  81597. // - depth map (for depth-of-field)
  81598. // - grain texture
  81599. /**
  81600. * The chromatic aberration PostProcess id in the pipeline
  81601. */
  81602. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81603. /**
  81604. * The highlights enhancing PostProcess id in the pipeline
  81605. */
  81606. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81607. /**
  81608. * The depth-of-field PostProcess id in the pipeline
  81609. */
  81610. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81611. _this._scene = scene;
  81612. // Fetch texture samplers
  81613. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81614. if (parameters.grain_texture) {
  81615. _this._grainTexture = parameters.grain_texture;
  81616. }
  81617. else {
  81618. _this._createGrainTexture();
  81619. }
  81620. // save parameters
  81621. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81622. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81623. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81624. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81625. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81626. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81627. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81628. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81629. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81630. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81631. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81632. // Create effects
  81633. _this._createChromaticAberrationPostProcess(ratio);
  81634. _this._createHighlightsPostProcess(ratio);
  81635. _this._createDepthOfFieldPostProcess(ratio / 4);
  81636. // Set up pipeline
  81637. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  81638. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  81639. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  81640. if (_this._highlightsGain === -1) {
  81641. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  81642. }
  81643. // Finish
  81644. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81645. if (cameras) {
  81646. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81647. }
  81648. return _this;
  81649. }
  81650. // public methods (self explanatory)
  81651. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  81652. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  81653. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  81654. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  81655. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  81656. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  81657. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  81658. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  81659. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  81660. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  81661. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  81662. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  81663. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  81664. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  81665. };
  81666. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  81667. this._highlightsPostProcess.updateEffect();
  81668. };
  81669. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  81670. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  81671. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  81672. this._highlightsGain = amount;
  81673. };
  81674. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  81675. if (this._highlightsGain === -1) {
  81676. this._highlightsGain = 1.0;
  81677. }
  81678. this._highlightsThreshold = amount;
  81679. };
  81680. LensRenderingPipeline.prototype.disableHighlights = function () {
  81681. this._highlightsGain = -1;
  81682. };
  81683. /**
  81684. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  81685. */
  81686. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81687. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81688. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81689. this._chromaticAberrationPostProcess = null;
  81690. this._highlightsPostProcess = null;
  81691. this._depthOfFieldPostProcess = null;
  81692. this._grainTexture.dispose();
  81693. if (disableDepthRender)
  81694. this._scene.disableDepthRenderer();
  81695. };
  81696. // colors shifting and distortion
  81697. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  81698. var _this = this;
  81699. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  81700. [], // samplers
  81701. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81702. this._chromaticAberrationPostProcess.onApply = function (effect) {
  81703. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  81704. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81705. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81706. effect.setFloat('radialIntensity', 1);
  81707. effect.setFloat2('direction', 17, 17);
  81708. effect.setFloat2('centerPosition', 0.5, 0.5);
  81709. };
  81710. };
  81711. // highlights enhancing
  81712. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  81713. var _this = this;
  81714. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  81715. [], // samplers
  81716. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  81717. this._highlightsPostProcess.onApply = function (effect) {
  81718. effect.setFloat('gain', _this._highlightsGain);
  81719. effect.setFloat('threshold', _this._highlightsThreshold);
  81720. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  81721. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81722. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81723. };
  81724. };
  81725. // colors shifting and distortion
  81726. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  81727. var _this = this;
  81728. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  81729. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  81730. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  81731. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81732. this._depthOfFieldPostProcess.onApply = function (effect) {
  81733. effect.setTexture("depthSampler", _this._depthTexture);
  81734. effect.setTexture("grainSampler", _this._grainTexture);
  81735. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  81736. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  81737. effect.setFloat('grain_amount', _this._grainAmount);
  81738. effect.setBool('blur_noise', _this._blurNoise);
  81739. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81740. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81741. effect.setFloat('distortion', _this._distortion);
  81742. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  81743. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  81744. effect.setFloat('aperture', _this._dofAperture);
  81745. effect.setFloat('darken', _this._dofDarken);
  81746. effect.setFloat('edge_blur', _this._edgeBlur);
  81747. effect.setBool('highlights', (_this._highlightsGain !== -1));
  81748. if (_this._scene.activeCamera) {
  81749. effect.setFloat('near', _this._scene.activeCamera.minZ);
  81750. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  81751. }
  81752. };
  81753. };
  81754. // creates a black and white random noise texture, 512x512
  81755. LensRenderingPipeline.prototype._createGrainTexture = function () {
  81756. var size = 512;
  81757. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81758. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81759. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81760. var context = this._grainTexture.getContext();
  81761. var rand = function (min, max) {
  81762. return Math.random() * (max - min) + min;
  81763. };
  81764. var value;
  81765. for (var x = 0; x < size; x++) {
  81766. for (var y = 0; y < size; y++) {
  81767. value = Math.floor(rand(0.42, 0.58) * 255);
  81768. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  81769. context.fillRect(x, y, 1, 1);
  81770. }
  81771. }
  81772. this._grainTexture.update(false);
  81773. };
  81774. return LensRenderingPipeline;
  81775. }(BABYLON.PostProcessRenderPipeline));
  81776. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  81777. })(BABYLON || (BABYLON = {}));
  81778. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  81779. var BABYLON;
  81780. (function (BABYLON) {
  81781. var StandardRenderingPipeline = /** @class */ (function (_super) {
  81782. __extends(StandardRenderingPipeline, _super);
  81783. /**
  81784. * @constructor
  81785. * @param {string} name - The rendering pipeline name
  81786. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81787. * @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)
  81788. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  81789. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81790. */
  81791. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  81792. if (originalPostProcess === void 0) { originalPostProcess = null; }
  81793. var _this = _super.call(this, scene.getEngine(), name) || this;
  81794. /**
  81795. * Post-process used to down scale an image x4
  81796. */
  81797. _this.downSampleX4PostProcess = null;
  81798. /**
  81799. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  81800. */
  81801. _this.brightPassPostProcess = null;
  81802. /**
  81803. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  81804. */
  81805. _this.blurHPostProcesses = [];
  81806. /**
  81807. * Post-process array storing all the vertical blur post-processes used by the pipeline
  81808. */
  81809. _this.blurVPostProcesses = [];
  81810. /**
  81811. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  81812. */
  81813. _this.textureAdderPostProcess = null;
  81814. /**
  81815. * Post-process used to create volumetric lighting effect
  81816. */
  81817. _this.volumetricLightPostProcess = null;
  81818. /**
  81819. * Post-process used to smooth the previous volumetric light post-process on the X axis
  81820. */
  81821. _this.volumetricLightSmoothXPostProcess = null;
  81822. /**
  81823. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  81824. */
  81825. _this.volumetricLightSmoothYPostProcess = null;
  81826. /**
  81827. * Post-process used to merge the volumetric light effect and the real scene color
  81828. */
  81829. _this.volumetricLightMergePostProces = null;
  81830. /**
  81831. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  81832. */
  81833. _this.volumetricLightFinalPostProcess = null;
  81834. /**
  81835. * Base post-process used to calculate the average luminance of the final image for HDR
  81836. */
  81837. _this.luminancePostProcess = null;
  81838. /**
  81839. * Post-processes used to create down sample post-processes in order to get
  81840. * the average luminance of the final image for HDR
  81841. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  81842. */
  81843. _this.luminanceDownSamplePostProcesses = [];
  81844. /**
  81845. * Post-process used to create a HDR effect (light adaptation)
  81846. */
  81847. _this.hdrPostProcess = null;
  81848. /**
  81849. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  81850. */
  81851. _this.textureAdderFinalPostProcess = null;
  81852. /**
  81853. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  81854. */
  81855. _this.lensFlareFinalPostProcess = null;
  81856. /**
  81857. * Post-process used to merge the final HDR post-process and the real scene color
  81858. */
  81859. _this.hdrFinalPostProcess = null;
  81860. /**
  81861. * Post-process used to create a lens flare effect
  81862. */
  81863. _this.lensFlarePostProcess = null;
  81864. /**
  81865. * Post-process that merges the result of the lens flare post-process and the real scene color
  81866. */
  81867. _this.lensFlareComposePostProcess = null;
  81868. /**
  81869. * Post-process used to create a motion blur effect
  81870. */
  81871. _this.motionBlurPostProcess = null;
  81872. /**
  81873. * Post-process used to create a depth of field effect
  81874. */
  81875. _this.depthOfFieldPostProcess = null;
  81876. /**
  81877. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81878. */
  81879. _this.fxaaPostProcess = null;
  81880. // Values
  81881. /**
  81882. * Represents the brightness threshold in order to configure the illuminated surfaces
  81883. */
  81884. _this.brightThreshold = 1.0;
  81885. /**
  81886. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81887. */
  81888. _this.blurWidth = 512.0;
  81889. /**
  81890. * Sets if the blur for highlighted surfaces must be only horizontal
  81891. */
  81892. _this.horizontalBlur = false;
  81893. /**
  81894. * Sets the overall exposure used by the pipeline
  81895. */
  81896. _this.exposure = 1.0;
  81897. /**
  81898. * Texture used typically to simulate "dirty" on camera lens
  81899. */
  81900. _this.lensTexture = null;
  81901. /**
  81902. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81903. */
  81904. _this.volumetricLightCoefficient = 0.2;
  81905. /**
  81906. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81907. */
  81908. _this.volumetricLightPower = 4.0;
  81909. /**
  81910. * Used the set the blur intensity to smooth the volumetric lights
  81911. */
  81912. _this.volumetricLightBlurScale = 64.0;
  81913. /**
  81914. * Light (spot or directional) used to generate the volumetric lights rays
  81915. * The source light must have a shadow generate so the pipeline can get its
  81916. * depth map
  81917. */
  81918. _this.sourceLight = null;
  81919. /**
  81920. * For eye adaptation, represents the minimum luminance the eye can see
  81921. */
  81922. _this.hdrMinimumLuminance = 1.0;
  81923. /**
  81924. * For eye adaptation, represents the decrease luminance speed
  81925. */
  81926. _this.hdrDecreaseRate = 0.5;
  81927. /**
  81928. * For eye adaptation, represents the increase luminance speed
  81929. */
  81930. _this.hdrIncreaseRate = 0.5;
  81931. /**
  81932. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81933. */
  81934. _this.lensColorTexture = null;
  81935. /**
  81936. * The overall strengh for the lens flare effect
  81937. */
  81938. _this.lensFlareStrength = 20.0;
  81939. /**
  81940. * Dispersion coefficient for lens flare ghosts
  81941. */
  81942. _this.lensFlareGhostDispersal = 1.4;
  81943. /**
  81944. * Main lens flare halo width
  81945. */
  81946. _this.lensFlareHaloWidth = 0.7;
  81947. /**
  81948. * Based on the lens distortion effect, defines how much the lens flare result
  81949. * is distorted
  81950. */
  81951. _this.lensFlareDistortionStrength = 16.0;
  81952. /**
  81953. * Lens star texture must be used to simulate rays on the flares and is available
  81954. * in the documentation
  81955. */
  81956. _this.lensStarTexture = null;
  81957. /**
  81958. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81959. * flare effect by taking account of the dirt texture
  81960. */
  81961. _this.lensFlareDirtTexture = null;
  81962. /**
  81963. * Represents the focal length for the depth of field effect
  81964. */
  81965. _this.depthOfFieldDistance = 10.0;
  81966. /**
  81967. * Represents the blur intensity for the blurred part of the depth of field effect
  81968. */
  81969. _this.depthOfFieldBlurWidth = 64.0;
  81970. /**
  81971. * For motion blur, defines how much the image is blurred by the movement
  81972. */
  81973. _this.motionStrength = 1.0;
  81974. /**
  81975. * List of animations for the pipeline (IAnimatable implementation)
  81976. */
  81977. _this.animations = [];
  81978. _this._currentDepthOfFieldSource = null;
  81979. _this._hdrCurrentLuminance = 1.0;
  81980. // Getters and setters
  81981. _this._bloomEnabled = false;
  81982. _this._depthOfFieldEnabled = false;
  81983. _this._vlsEnabled = false;
  81984. _this._lensFlareEnabled = false;
  81985. _this._hdrEnabled = false;
  81986. _this._motionBlurEnabled = false;
  81987. _this._fxaaEnabled = false;
  81988. _this._motionBlurSamples = 64.0;
  81989. _this._volumetricLightStepsCount = 50.0;
  81990. _this._samples = 1;
  81991. _this._cameras = cameras || [];
  81992. // Initialize
  81993. _this._scene = scene;
  81994. _this._basePostProcess = originalPostProcess;
  81995. _this._ratio = ratio;
  81996. // Misc
  81997. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81998. // Finish
  81999. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82000. _this._buildPipeline();
  82001. return _this;
  82002. }
  82003. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  82004. /**
  82005. * Specifies if the bloom pipeline is enabled
  82006. */
  82007. get: function () {
  82008. return this._bloomEnabled;
  82009. },
  82010. set: function (enabled) {
  82011. if (this._bloomEnabled === enabled) {
  82012. return;
  82013. }
  82014. this._bloomEnabled = enabled;
  82015. this._buildPipeline();
  82016. },
  82017. enumerable: true,
  82018. configurable: true
  82019. });
  82020. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  82021. /**
  82022. * Specifies if the depth of field pipeline is enabed
  82023. */
  82024. get: function () {
  82025. return this._depthOfFieldEnabled;
  82026. },
  82027. set: function (enabled) {
  82028. if (this._depthOfFieldEnabled === enabled) {
  82029. return;
  82030. }
  82031. this._depthOfFieldEnabled = enabled;
  82032. this._buildPipeline();
  82033. },
  82034. enumerable: true,
  82035. configurable: true
  82036. });
  82037. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  82038. /**
  82039. * Specifies if the lens flare pipeline is enabed
  82040. */
  82041. get: function () {
  82042. return this._lensFlareEnabled;
  82043. },
  82044. set: function (enabled) {
  82045. if (this._lensFlareEnabled === enabled) {
  82046. return;
  82047. }
  82048. this._lensFlareEnabled = enabled;
  82049. this._buildPipeline();
  82050. },
  82051. enumerable: true,
  82052. configurable: true
  82053. });
  82054. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  82055. /**
  82056. * Specifies if the HDR pipeline is enabled
  82057. */
  82058. get: function () {
  82059. return this._hdrEnabled;
  82060. },
  82061. set: function (enabled) {
  82062. if (this._hdrEnabled === enabled) {
  82063. return;
  82064. }
  82065. this._hdrEnabled = enabled;
  82066. this._buildPipeline();
  82067. },
  82068. enumerable: true,
  82069. configurable: true
  82070. });
  82071. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  82072. /**
  82073. * Specifies if the volumetric lights scattering effect is enabled
  82074. */
  82075. get: function () {
  82076. return this._vlsEnabled;
  82077. },
  82078. set: function (enabled) {
  82079. if (this._vlsEnabled === enabled) {
  82080. return;
  82081. }
  82082. if (enabled) {
  82083. var geometry = this._scene.enableGeometryBufferRenderer();
  82084. if (!geometry) {
  82085. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  82086. return;
  82087. }
  82088. }
  82089. this._vlsEnabled = enabled;
  82090. this._buildPipeline();
  82091. },
  82092. enumerable: true,
  82093. configurable: true
  82094. });
  82095. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  82096. /**
  82097. * Specifies if the motion blur effect is enabled
  82098. */
  82099. get: function () {
  82100. return this._motionBlurEnabled;
  82101. },
  82102. set: function (enabled) {
  82103. if (this._motionBlurEnabled === enabled) {
  82104. return;
  82105. }
  82106. this._motionBlurEnabled = enabled;
  82107. this._buildPipeline();
  82108. },
  82109. enumerable: true,
  82110. configurable: true
  82111. });
  82112. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  82113. /**
  82114. * Specifies if anti-aliasing is enabled
  82115. */
  82116. get: function () {
  82117. return this._fxaaEnabled;
  82118. },
  82119. set: function (enabled) {
  82120. if (this._fxaaEnabled === enabled) {
  82121. return;
  82122. }
  82123. this._fxaaEnabled = enabled;
  82124. this._buildPipeline();
  82125. },
  82126. enumerable: true,
  82127. configurable: true
  82128. });
  82129. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  82130. /**
  82131. * Specifies the number of steps used to calculate the volumetric lights
  82132. * Typically in interval [50, 200]
  82133. */
  82134. get: function () {
  82135. return this._volumetricLightStepsCount;
  82136. },
  82137. set: function (count) {
  82138. if (this.volumetricLightPostProcess) {
  82139. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  82140. }
  82141. this._volumetricLightStepsCount = count;
  82142. },
  82143. enumerable: true,
  82144. configurable: true
  82145. });
  82146. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  82147. /**
  82148. * Specifies the number of samples used for the motion blur effect
  82149. * Typically in interval [16, 64]
  82150. */
  82151. get: function () {
  82152. return this._motionBlurSamples;
  82153. },
  82154. set: function (samples) {
  82155. if (this.motionBlurPostProcess) {
  82156. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  82157. }
  82158. this._motionBlurSamples = samples;
  82159. },
  82160. enumerable: true,
  82161. configurable: true
  82162. });
  82163. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  82164. /**
  82165. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  82166. */
  82167. get: function () {
  82168. return this._samples;
  82169. },
  82170. set: function (sampleCount) {
  82171. if (this._samples === sampleCount) {
  82172. return;
  82173. }
  82174. this._samples = sampleCount;
  82175. this._buildPipeline();
  82176. },
  82177. enumerable: true,
  82178. configurable: true
  82179. });
  82180. StandardRenderingPipeline.prototype._buildPipeline = function () {
  82181. var _this = this;
  82182. var ratio = this._ratio;
  82183. var scene = this._scene;
  82184. this._disposePostProcesses();
  82185. this._reset();
  82186. // Create pass post-process
  82187. if (!this._basePostProcess) {
  82188. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  82189. this.originalPostProcess.onApply = function (effect) {
  82190. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  82191. };
  82192. }
  82193. else {
  82194. this.originalPostProcess = this._basePostProcess;
  82195. }
  82196. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  82197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  82198. }
  82199. this._currentDepthOfFieldSource = this.originalPostProcess;
  82200. if (this._bloomEnabled) {
  82201. // Create down sample X4 post-process
  82202. this._createDownSampleX4PostProcess(scene, ratio / 2);
  82203. // Create bright pass post-process
  82204. this._createBrightPassPostProcess(scene, ratio / 2);
  82205. // Create gaussian blur post-processes (down sampling blurs)
  82206. this._createBlurPostProcesses(scene, ratio / 4, 1);
  82207. // Create texture adder post-process
  82208. this._createTextureAdderPostProcess(scene, ratio);
  82209. // Create depth-of-field source post-process
  82210. 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);
  82211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  82212. }
  82213. if (this._vlsEnabled) {
  82214. // Create volumetric light
  82215. this._createVolumetricLightPostProcess(scene, ratio);
  82216. // Create volumetric light final post-process
  82217. 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);
  82218. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  82219. }
  82220. if (this._lensFlareEnabled) {
  82221. // Create lens flare post-process
  82222. this._createLensFlarePostProcess(scene, ratio);
  82223. // Create depth-of-field source post-process post lens-flare and disable it now
  82224. 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);
  82225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  82226. }
  82227. if (this._hdrEnabled) {
  82228. // Create luminance
  82229. this._createLuminancePostProcesses(scene, this._floatTextureType);
  82230. // Create HDR
  82231. this._createHdrPostProcess(scene, ratio);
  82232. // Create depth-of-field source post-process post hdr and disable it now
  82233. 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);
  82234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  82235. }
  82236. if (this._depthOfFieldEnabled) {
  82237. // Create gaussian blur used by depth-of-field
  82238. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  82239. // Create depth-of-field post-process
  82240. this._createDepthOfFieldPostProcess(scene, ratio);
  82241. }
  82242. if (this._motionBlurEnabled) {
  82243. // Create motion blur post-process
  82244. this._createMotionBlurPostProcess(scene, ratio);
  82245. }
  82246. if (this._fxaaEnabled) {
  82247. // Create fxaa post-process
  82248. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  82250. }
  82251. if (this._cameras !== null) {
  82252. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82253. }
  82254. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  82255. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82256. }
  82257. };
  82258. // Down Sample X4 Post-Processs
  82259. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  82260. var _this = this;
  82261. var downSampleX4Offsets = new Array(32);
  82262. 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);
  82263. this.downSampleX4PostProcess.onApply = function (effect) {
  82264. var id = 0;
  82265. var width = _this.downSampleX4PostProcess.width;
  82266. var height = _this.downSampleX4PostProcess.height;
  82267. for (var i = -2; i < 2; i++) {
  82268. for (var j = -2; j < 2; j++) {
  82269. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  82270. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  82271. id += 2;
  82272. }
  82273. }
  82274. effect.setArray2("dsOffsets", downSampleX4Offsets);
  82275. };
  82276. // Add to pipeline
  82277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  82278. };
  82279. // Brightpass Post-Process
  82280. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  82281. var _this = this;
  82282. var brightOffsets = new Array(8);
  82283. 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);
  82284. this.brightPassPostProcess.onApply = function (effect) {
  82285. var sU = (1.0 / _this.brightPassPostProcess.width);
  82286. var sV = (1.0 / _this.brightPassPostProcess.height);
  82287. brightOffsets[0] = -0.5 * sU;
  82288. brightOffsets[1] = 0.5 * sV;
  82289. brightOffsets[2] = 0.5 * sU;
  82290. brightOffsets[3] = 0.5 * sV;
  82291. brightOffsets[4] = -0.5 * sU;
  82292. brightOffsets[5] = -0.5 * sV;
  82293. brightOffsets[6] = 0.5 * sU;
  82294. brightOffsets[7] = -0.5 * sV;
  82295. effect.setArray2("dsOffsets", brightOffsets);
  82296. effect.setFloat("brightThreshold", _this.brightThreshold);
  82297. };
  82298. // Add to pipeline
  82299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  82300. };
  82301. // Create blur H&V post-processes
  82302. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  82303. var _this = this;
  82304. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  82305. var engine = scene.getEngine();
  82306. 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);
  82307. 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);
  82308. blurX.onActivateObservable.add(function () {
  82309. var dw = blurX.width / engine.getRenderWidth();
  82310. blurX.kernel = _this[blurWidthKey] * dw;
  82311. });
  82312. blurY.onActivateObservable.add(function () {
  82313. var dw = blurY.height / engine.getRenderHeight();
  82314. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  82315. });
  82316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  82317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  82318. this.blurHPostProcesses.push(blurX);
  82319. this.blurVPostProcesses.push(blurY);
  82320. };
  82321. // Create texture adder post-process
  82322. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  82323. var _this = this;
  82324. 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);
  82325. this.textureAdderPostProcess.onApply = function (effect) {
  82326. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  82327. effect.setTexture("lensSampler", _this.lensTexture);
  82328. effect.setFloat("exposure", _this.exposure);
  82329. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  82330. };
  82331. // Add to pipeline
  82332. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  82333. };
  82334. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  82335. var _this = this;
  82336. var geometryRenderer = scene.enableGeometryBufferRenderer();
  82337. geometryRenderer.enablePosition = true;
  82338. var geometry = geometryRenderer.getGBuffer();
  82339. // Base post-process
  82340. 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));
  82341. var depthValues = BABYLON.Vector2.Zero();
  82342. this.volumetricLightPostProcess.onApply = function (effect) {
  82343. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  82344. var generator = _this.sourceLight.getShadowGenerator();
  82345. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  82346. effect.setTexture("positionSampler", geometry.textures[2]);
  82347. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  82348. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  82349. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  82350. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  82351. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  82352. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  82353. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  82354. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  82355. effect.setVector2("depthValues", depthValues);
  82356. }
  82357. };
  82358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  82359. // Smooth
  82360. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  82361. // Merge
  82362. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  82363. this.volumetricLightMergePostProces.onApply = function (effect) {
  82364. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  82365. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  82366. };
  82367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  82368. };
  82369. // Create luminance
  82370. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  82371. var _this = this;
  82372. // Create luminance
  82373. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  82374. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  82375. var offsets = [];
  82376. this.luminancePostProcess.onApply = function (effect) {
  82377. var sU = (1.0 / _this.luminancePostProcess.width);
  82378. var sV = (1.0 / _this.luminancePostProcess.height);
  82379. offsets[0] = -0.5 * sU;
  82380. offsets[1] = 0.5 * sV;
  82381. offsets[2] = 0.5 * sU;
  82382. offsets[3] = 0.5 * sV;
  82383. offsets[4] = -0.5 * sU;
  82384. offsets[5] = -0.5 * sV;
  82385. offsets[6] = 0.5 * sU;
  82386. offsets[7] = -0.5 * sV;
  82387. effect.setArray2("lumOffsets", offsets);
  82388. };
  82389. // Add to pipeline
  82390. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  82391. // Create down sample luminance
  82392. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  82393. var size = Math.pow(3, i);
  82394. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  82395. if (i === 0) {
  82396. defines += "#define FINAL_DOWN_SAMPLER";
  82397. }
  82398. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  82399. this.luminanceDownSamplePostProcesses.push(postProcess);
  82400. }
  82401. // Create callbacks and add effects
  82402. var lastLuminance = this.luminancePostProcess;
  82403. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  82404. var downSampleOffsets = new Array(18);
  82405. pp.onApply = function (effect) {
  82406. if (!lastLuminance) {
  82407. return;
  82408. }
  82409. var id = 0;
  82410. for (var x = -1; x < 2; x++) {
  82411. for (var y = -1; y < 2; y++) {
  82412. downSampleOffsets[id] = x / lastLuminance.width;
  82413. downSampleOffsets[id + 1] = y / lastLuminance.height;
  82414. id += 2;
  82415. }
  82416. }
  82417. effect.setArray2("dsOffsets", downSampleOffsets);
  82418. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  82419. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82420. lastLuminance = _this.luminancePostProcess;
  82421. }
  82422. else {
  82423. lastLuminance = pp;
  82424. }
  82425. };
  82426. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82427. pp.onAfterRender = function (effect) {
  82428. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  82429. 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);
  82430. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  82431. };
  82432. }
  82433. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  82434. });
  82435. };
  82436. // Create HDR post-process
  82437. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  82438. var _this = this;
  82439. 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);
  82440. var outputLiminance = 1;
  82441. var time = 0;
  82442. var lastTime = 0;
  82443. this.hdrPostProcess.onApply = function (effect) {
  82444. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  82445. time += scene.getEngine().getDeltaTime();
  82446. if (outputLiminance < 0) {
  82447. outputLiminance = _this._hdrCurrentLuminance;
  82448. }
  82449. else {
  82450. var dt = (lastTime - time) / 1000.0;
  82451. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  82452. outputLiminance += _this.hdrDecreaseRate * dt;
  82453. }
  82454. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  82455. outputLiminance -= _this.hdrIncreaseRate * dt;
  82456. }
  82457. else {
  82458. outputLiminance = _this._hdrCurrentLuminance;
  82459. }
  82460. }
  82461. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  82462. effect.setFloat("averageLuminance", outputLiminance);
  82463. lastTime = time;
  82464. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  82465. };
  82466. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  82467. };
  82468. // Create lens flare post-process
  82469. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  82470. var _this = this;
  82471. 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);
  82472. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  82473. this._createBlurPostProcesses(scene, ratio / 4, 2);
  82474. 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);
  82475. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  82476. var resolution = new BABYLON.Vector2(0, 0);
  82477. // Lens flare
  82478. this.lensFlarePostProcess.onApply = function (effect) {
  82479. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  82480. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  82481. effect.setFloat("strength", _this.lensFlareStrength);
  82482. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  82483. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  82484. // Shift
  82485. resolution.x = _this.lensFlarePostProcess.width;
  82486. resolution.y = _this.lensFlarePostProcess.height;
  82487. effect.setVector2("resolution", resolution);
  82488. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  82489. };
  82490. // Compose
  82491. 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);
  82492. 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);
  82493. this.lensFlareComposePostProcess.onApply = function (effect) {
  82494. if (!_this._scene.activeCamera) {
  82495. return;
  82496. }
  82497. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82498. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  82499. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  82500. // Lens start rotation matrix
  82501. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  82502. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  82503. 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));
  82504. camRot *= 4.0;
  82505. 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);
  82506. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  82507. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  82508. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  82509. };
  82510. };
  82511. // Create depth-of-field post-process
  82512. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82513. var _this = this;
  82514. 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);
  82515. this.depthOfFieldPostProcess.onApply = function (effect) {
  82516. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82517. effect.setTexture("depthSampler", _this._getDepthTexture());
  82518. effect.setFloat("distance", _this.depthOfFieldDistance);
  82519. };
  82520. // Add to pipeline
  82521. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82522. };
  82523. // Create motion blur post-process
  82524. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82525. var _this = this;
  82526. 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);
  82527. var motionScale = 0;
  82528. var prevViewProjection = BABYLON.Matrix.Identity();
  82529. var invViewProjection = BABYLON.Matrix.Identity();
  82530. var viewProjection = BABYLON.Matrix.Identity();
  82531. var screenSize = BABYLON.Vector2.Zero();
  82532. this.motionBlurPostProcess.onApply = function (effect) {
  82533. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82534. viewProjection.invertToRef(invViewProjection);
  82535. effect.setMatrix("inverseViewProjection", invViewProjection);
  82536. effect.setMatrix("prevViewProjection", prevViewProjection);
  82537. prevViewProjection = viewProjection;
  82538. screenSize.x = _this.motionBlurPostProcess.width;
  82539. screenSize.y = _this.motionBlurPostProcess.height;
  82540. effect.setVector2("screenSize", screenSize);
  82541. motionScale = scene.getEngine().getFps() / 60.0;
  82542. effect.setFloat("motionScale", motionScale);
  82543. effect.setFloat("motionStrength", _this.motionStrength);
  82544. effect.setTexture("depthSampler", _this._getDepthTexture());
  82545. };
  82546. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82547. };
  82548. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82549. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82550. var renderer = this._scene.enableGeometryBufferRenderer();
  82551. return renderer.getGBuffer().textures[0];
  82552. }
  82553. return this._scene.enableDepthRenderer().getDepthMap();
  82554. };
  82555. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82556. for (var i = 0; i < this._cameras.length; i++) {
  82557. var camera = this._cameras[i];
  82558. if (this.originalPostProcess) {
  82559. this.originalPostProcess.dispose(camera);
  82560. }
  82561. if (this.downSampleX4PostProcess) {
  82562. this.downSampleX4PostProcess.dispose(camera);
  82563. }
  82564. if (this.brightPassPostProcess) {
  82565. this.brightPassPostProcess.dispose(camera);
  82566. }
  82567. if (this.textureAdderPostProcess) {
  82568. this.textureAdderPostProcess.dispose(camera);
  82569. }
  82570. if (this.textureAdderFinalPostProcess) {
  82571. this.textureAdderFinalPostProcess.dispose(camera);
  82572. }
  82573. if (this.volumetricLightPostProcess) {
  82574. this.volumetricLightPostProcess.dispose(camera);
  82575. }
  82576. if (this.volumetricLightSmoothXPostProcess) {
  82577. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82578. }
  82579. if (this.volumetricLightSmoothYPostProcess) {
  82580. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82581. }
  82582. if (this.volumetricLightMergePostProces) {
  82583. this.volumetricLightMergePostProces.dispose(camera);
  82584. }
  82585. if (this.volumetricLightFinalPostProcess) {
  82586. this.volumetricLightFinalPostProcess.dispose(camera);
  82587. }
  82588. if (this.lensFlarePostProcess) {
  82589. this.lensFlarePostProcess.dispose(camera);
  82590. }
  82591. if (this.lensFlareComposePostProcess) {
  82592. this.lensFlareComposePostProcess.dispose(camera);
  82593. }
  82594. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82595. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82596. }
  82597. if (this.luminancePostProcess) {
  82598. this.luminancePostProcess.dispose(camera);
  82599. }
  82600. if (this.hdrPostProcess) {
  82601. this.hdrPostProcess.dispose(camera);
  82602. }
  82603. if (this.hdrFinalPostProcess) {
  82604. this.hdrFinalPostProcess.dispose(camera);
  82605. }
  82606. if (this.depthOfFieldPostProcess) {
  82607. this.depthOfFieldPostProcess.dispose(camera);
  82608. }
  82609. if (this.motionBlurPostProcess) {
  82610. this.motionBlurPostProcess.dispose(camera);
  82611. }
  82612. if (this.fxaaPostProcess) {
  82613. this.fxaaPostProcess.dispose(camera);
  82614. }
  82615. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82616. this.blurHPostProcesses[j].dispose(camera);
  82617. }
  82618. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82619. this.blurVPostProcesses[j].dispose(camera);
  82620. }
  82621. }
  82622. this.originalPostProcess = null;
  82623. this.downSampleX4PostProcess = null;
  82624. this.brightPassPostProcess = null;
  82625. this.textureAdderPostProcess = null;
  82626. this.textureAdderFinalPostProcess = null;
  82627. this.volumetricLightPostProcess = null;
  82628. this.volumetricLightSmoothXPostProcess = null;
  82629. this.volumetricLightSmoothYPostProcess = null;
  82630. this.volumetricLightMergePostProces = null;
  82631. this.volumetricLightFinalPostProcess = null;
  82632. this.lensFlarePostProcess = null;
  82633. this.lensFlareComposePostProcess = null;
  82634. this.luminancePostProcess = null;
  82635. this.hdrPostProcess = null;
  82636. this.hdrFinalPostProcess = null;
  82637. this.depthOfFieldPostProcess = null;
  82638. this.motionBlurPostProcess = null;
  82639. this.fxaaPostProcess = null;
  82640. this.luminanceDownSamplePostProcesses = [];
  82641. this.blurHPostProcesses = [];
  82642. this.blurVPostProcesses = [];
  82643. };
  82644. /**
  82645. * Dispose of the pipeline and stop all post processes
  82646. */
  82647. StandardRenderingPipeline.prototype.dispose = function () {
  82648. this._disposePostProcesses();
  82649. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82650. _super.prototype.dispose.call(this);
  82651. };
  82652. /**
  82653. * Serialize the rendering pipeline (Used when exporting)
  82654. * @returns the serialized object
  82655. */
  82656. StandardRenderingPipeline.prototype.serialize = function () {
  82657. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82658. if (this.sourceLight) {
  82659. serializationObject.sourceLightId = this.sourceLight.id;
  82660. }
  82661. serializationObject.customType = "StandardRenderingPipeline";
  82662. return serializationObject;
  82663. };
  82664. /**
  82665. * Parse the serialized pipeline
  82666. * @param source Source pipeline.
  82667. * @param scene The scene to load the pipeline to.
  82668. * @param rootUrl The URL of the serialized pipeline.
  82669. * @returns An instantiated pipeline from the serialized object.
  82670. */
  82671. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82672. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82673. if (source.sourceLightId) {
  82674. p.sourceLight = scene.getLightByID(source.sourceLightId);
  82675. }
  82676. return p;
  82677. };
  82678. // Luminance steps
  82679. StandardRenderingPipeline.LuminanceSteps = 6;
  82680. __decorate([
  82681. BABYLON.serialize()
  82682. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  82683. __decorate([
  82684. BABYLON.serialize()
  82685. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  82686. __decorate([
  82687. BABYLON.serialize()
  82688. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  82689. __decorate([
  82690. BABYLON.serialize()
  82691. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  82692. __decorate([
  82693. BABYLON.serializeAsTexture("lensTexture")
  82694. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  82695. __decorate([
  82696. BABYLON.serialize()
  82697. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  82698. __decorate([
  82699. BABYLON.serialize()
  82700. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  82701. __decorate([
  82702. BABYLON.serialize()
  82703. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  82704. __decorate([
  82705. BABYLON.serialize()
  82706. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  82707. __decorate([
  82708. BABYLON.serialize()
  82709. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  82710. __decorate([
  82711. BABYLON.serialize()
  82712. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  82713. __decorate([
  82714. BABYLON.serializeAsTexture("lensColorTexture")
  82715. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  82716. __decorate([
  82717. BABYLON.serialize()
  82718. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  82719. __decorate([
  82720. BABYLON.serialize()
  82721. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  82722. __decorate([
  82723. BABYLON.serialize()
  82724. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  82725. __decorate([
  82726. BABYLON.serialize()
  82727. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  82728. __decorate([
  82729. BABYLON.serializeAsTexture("lensStarTexture")
  82730. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  82731. __decorate([
  82732. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  82733. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  82734. __decorate([
  82735. BABYLON.serialize()
  82736. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  82737. __decorate([
  82738. BABYLON.serialize()
  82739. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  82740. __decorate([
  82741. BABYLON.serialize()
  82742. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  82743. __decorate([
  82744. BABYLON.serialize()
  82745. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  82746. __decorate([
  82747. BABYLON.serialize()
  82748. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  82749. __decorate([
  82750. BABYLON.serialize()
  82751. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  82752. __decorate([
  82753. BABYLON.serialize()
  82754. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  82755. __decorate([
  82756. BABYLON.serialize()
  82757. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  82758. __decorate([
  82759. BABYLON.serialize()
  82760. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  82761. __decorate([
  82762. BABYLON.serialize()
  82763. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  82764. __decorate([
  82765. BABYLON.serialize()
  82766. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  82767. __decorate([
  82768. BABYLON.serialize()
  82769. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  82770. __decorate([
  82771. BABYLON.serialize()
  82772. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  82773. __decorate([
  82774. BABYLON.serialize()
  82775. ], StandardRenderingPipeline.prototype, "samples", null);
  82776. return StandardRenderingPipeline;
  82777. }(BABYLON.PostProcessRenderPipeline));
  82778. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  82779. })(BABYLON || (BABYLON = {}));
  82780. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  82781. var BABYLON;
  82782. (function (BABYLON) {
  82783. var FxaaPostProcess = /** @class */ (function (_super) {
  82784. __extends(FxaaPostProcess, _super);
  82785. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82786. if (camera === void 0) { camera = null; }
  82787. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82788. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  82789. var defines = _this._getDefines();
  82790. _this.updateEffect(defines);
  82791. _this.onApplyObservable.add(function (effect) {
  82792. var texelSize = _this.texelSize;
  82793. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  82794. });
  82795. return _this;
  82796. }
  82797. FxaaPostProcess.prototype._getDefines = function () {
  82798. var engine = this.getEngine();
  82799. if (!engine) {
  82800. return null;
  82801. }
  82802. var glInfo = engine.getGlInfo();
  82803. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  82804. return "#define MALI 1\n";
  82805. }
  82806. return null;
  82807. };
  82808. return FxaaPostProcess;
  82809. }(BABYLON.PostProcess));
  82810. BABYLON.FxaaPostProcess = FxaaPostProcess;
  82811. })(BABYLON || (BABYLON = {}));
  82812. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  82813. var BABYLON;
  82814. (function (BABYLON) {
  82815. /**
  82816. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  82817. */
  82818. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  82819. __extends(ChromaticAberrationPostProcess, _super);
  82820. /**
  82821. * Creates a new instance ChromaticAberrationPostProcess
  82822. * @param name The name of the effect.
  82823. * @param screenWidth The width of the screen to apply the effect on.
  82824. * @param screenHeight The height of the screen to apply the effect on.
  82825. * @param options The required width/height ratio to downsize to before computing the render pass.
  82826. * @param camera The camera to apply the render pass to.
  82827. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82828. * @param engine The engine which the post process will be applied. (default: current engine)
  82829. * @param reusable If the post process can be reused on the same frame. (default: false)
  82830. * @param textureType Type of textures used when performing the post process. (default: 0)
  82831. * @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)
  82832. */
  82833. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82834. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82835. if (blockCompilation === void 0) { blockCompilation = false; }
  82836. 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;
  82837. /**
  82838. * The amount of seperation of rgb channels (default: 30)
  82839. */
  82840. _this.aberrationAmount = 30;
  82841. /**
  82842. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  82843. */
  82844. _this.radialIntensity = 0;
  82845. /**
  82846. * 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))
  82847. */
  82848. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  82849. /**
  82850. * 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))
  82851. */
  82852. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  82853. _this.onApplyObservable.add(function (effect) {
  82854. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  82855. effect.setFloat('screen_width', screenWidth);
  82856. effect.setFloat('screen_height', screenHeight);
  82857. effect.setFloat('radialIntensity', _this.radialIntensity);
  82858. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  82859. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  82860. });
  82861. return _this;
  82862. }
  82863. return ChromaticAberrationPostProcess;
  82864. }(BABYLON.PostProcess));
  82865. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  82866. })(BABYLON || (BABYLON = {}));
  82867. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  82868. var BABYLON;
  82869. (function (BABYLON) {
  82870. /**
  82871. * The GrainPostProcess adds noise to the image at mid luminance levels
  82872. */
  82873. var GrainPostProcess = /** @class */ (function (_super) {
  82874. __extends(GrainPostProcess, _super);
  82875. /**
  82876. * Creates a new instance of @see GrainPostProcess
  82877. * @param name The name of the effect.
  82878. * @param options The required width/height ratio to downsize to before computing the render pass.
  82879. * @param camera The camera to apply the render pass to.
  82880. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82881. * @param engine The engine which the post process will be applied. (default: current engine)
  82882. * @param reusable If the post process can be reused on the same frame. (default: false)
  82883. * @param textureType Type of textures used when performing the post process. (default: 0)
  82884. * @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)
  82885. */
  82886. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82887. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82888. if (blockCompilation === void 0) { blockCompilation = false; }
  82889. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82890. /**
  82891. * The intensity of the grain added (default: 30)
  82892. */
  82893. _this.intensity = 30;
  82894. /**
  82895. * If the grain should be randomized on every frame
  82896. */
  82897. _this.animated = false;
  82898. _this.onApplyObservable.add(function (effect) {
  82899. effect.setFloat('intensity', _this.intensity);
  82900. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82901. });
  82902. return _this;
  82903. }
  82904. return GrainPostProcess;
  82905. }(BABYLON.PostProcess));
  82906. BABYLON.GrainPostProcess = GrainPostProcess;
  82907. })(BABYLON || (BABYLON = {}));
  82908. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82909. var BABYLON;
  82910. (function (BABYLON) {
  82911. /**
  82912. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82913. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82914. */
  82915. var SharpenPostProcess = /** @class */ (function (_super) {
  82916. __extends(SharpenPostProcess, _super);
  82917. /**
  82918. * Creates a new instance ConvolutionPostProcess
  82919. * @param name The name of the effect.
  82920. * @param options The required width/height ratio to downsize to before computing the render pass.
  82921. * @param camera The camera to apply the render pass to.
  82922. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82923. * @param engine The engine which the post process will be applied. (default: current engine)
  82924. * @param reusable If the post process can be reused on the same frame. (default: false)
  82925. * @param textureType Type of textures used when performing the post process. (default: 0)
  82926. * @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)
  82927. */
  82928. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82929. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82930. if (blockCompilation === void 0) { blockCompilation = false; }
  82931. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82932. /**
  82933. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82934. */
  82935. _this.colorAmount = 1.0;
  82936. /**
  82937. * How much sharpness should be applied (default: 0.3)
  82938. */
  82939. _this.edgeAmount = 0.3;
  82940. _this.onApply = function (effect) {
  82941. effect.setFloat2("screenSize", _this.width, _this.height);
  82942. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82943. };
  82944. return _this;
  82945. }
  82946. return SharpenPostProcess;
  82947. }(BABYLON.PostProcess));
  82948. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82949. })(BABYLON || (BABYLON = {}));
  82950. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82951. var BABYLON;
  82952. (function (BABYLON) {
  82953. /**
  82954. * The Blur Post Process which blurs an image based on a kernel and direction.
  82955. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82956. */
  82957. var BlurPostProcess = /** @class */ (function (_super) {
  82958. __extends(BlurPostProcess, _super);
  82959. /**
  82960. * Creates a new instance BlurPostProcess
  82961. * @param name The name of the effect.
  82962. * @param direction The direction in which to blur the image.
  82963. * @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.
  82964. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82965. * @param camera The camera to apply the render pass to.
  82966. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82967. * @param engine The engine which the post process will be applied. (default: current engine)
  82968. * @param reusable If the post process can be reused on the same frame. (default: false)
  82969. * @param textureType Type of textures used when performing the post process. (default: 0)
  82970. * @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)
  82971. */
  82972. function BlurPostProcess(name,
  82973. /** The direction in which to blur the image. */
  82974. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  82975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82976. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82977. if (defines === void 0) { defines = ""; }
  82978. if (blockCompilation === void 0) { blockCompilation = false; }
  82979. 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;
  82980. _this.direction = direction;
  82981. _this.blockCompilation = blockCompilation;
  82982. _this._packedFloat = false;
  82983. _this._staticDefines = "";
  82984. _this._staticDefines = defines;
  82985. _this.onApplyObservable.add(function (effect) {
  82986. if (_this._outputTexture) {
  82987. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  82988. }
  82989. else {
  82990. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  82991. }
  82992. });
  82993. _this.kernel = kernel;
  82994. return _this;
  82995. }
  82996. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  82997. /**
  82998. * Gets the length in pixels of the blur sample region
  82999. */
  83000. get: function () {
  83001. return this._idealKernel;
  83002. },
  83003. /**
  83004. * Sets the length in pixels of the blur sample region
  83005. */
  83006. set: function (v) {
  83007. if (this._idealKernel === v) {
  83008. return;
  83009. }
  83010. v = Math.max(v, 1);
  83011. this._idealKernel = v;
  83012. this._kernel = this._nearestBestKernel(v);
  83013. if (!this.blockCompilation) {
  83014. this._updateParameters();
  83015. }
  83016. },
  83017. enumerable: true,
  83018. configurable: true
  83019. });
  83020. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  83021. /**
  83022. * Gets wether or not the blur is unpacking/repacking floats
  83023. */
  83024. get: function () {
  83025. return this._packedFloat;
  83026. },
  83027. /**
  83028. * Sets wether or not the blur needs to unpack/repack floats
  83029. */
  83030. set: function (v) {
  83031. if (this._packedFloat === v) {
  83032. return;
  83033. }
  83034. this._packedFloat = v;
  83035. if (!this.blockCompilation) {
  83036. this._updateParameters();
  83037. }
  83038. },
  83039. enumerable: true,
  83040. configurable: true
  83041. });
  83042. /**
  83043. * Updates the effect with the current post process compile time values and recompiles the shader.
  83044. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83045. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83046. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83047. * @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
  83048. * @param onCompiled Called when the shader has been compiled.
  83049. * @param onError Called if there is an error when compiling a shader.
  83050. */
  83051. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83052. if (defines === void 0) { defines = null; }
  83053. if (uniforms === void 0) { uniforms = null; }
  83054. if (samplers === void 0) { samplers = null; }
  83055. this._updateParameters(onCompiled, onError);
  83056. };
  83057. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  83058. // Generate sampling offsets and weights
  83059. var N = this._kernel;
  83060. var centerIndex = (N - 1) / 2;
  83061. // Generate Gaussian sampling weights over kernel
  83062. var offsets = [];
  83063. var weights = [];
  83064. var totalWeight = 0;
  83065. for (var i = 0; i < N; i++) {
  83066. var u = i / (N - 1);
  83067. var w = this._gaussianWeight(u * 2.0 - 1);
  83068. offsets[i] = (i - centerIndex);
  83069. weights[i] = w;
  83070. totalWeight += w;
  83071. }
  83072. // Normalize weights
  83073. for (var i = 0; i < weights.length; i++) {
  83074. weights[i] /= totalWeight;
  83075. }
  83076. // Optimize: combine samples to take advantage of hardware linear sampling
  83077. // Walk from left to center, combining pairs (symmetrically)
  83078. var linearSamplingWeights = [];
  83079. var linearSamplingOffsets = [];
  83080. var linearSamplingMap = [];
  83081. for (var i = 0; i <= centerIndex; i += 2) {
  83082. var j = Math.min(i + 1, Math.floor(centerIndex));
  83083. var singleCenterSample = i === j;
  83084. if (singleCenterSample) {
  83085. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83086. }
  83087. else {
  83088. var sharedCell = j === centerIndex;
  83089. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  83090. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  83091. if (offsetLinear === 0) {
  83092. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83093. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  83094. }
  83095. else {
  83096. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  83097. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  83098. }
  83099. }
  83100. }
  83101. for (var i = 0; i < linearSamplingMap.length; i++) {
  83102. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  83103. linearSamplingWeights[i] = linearSamplingMap[i].w;
  83104. }
  83105. // Replace with optimized
  83106. offsets = linearSamplingOffsets;
  83107. weights = linearSamplingWeights;
  83108. // Generate shaders
  83109. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  83110. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  83111. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  83112. var defines = "";
  83113. defines += this._staticDefines;
  83114. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  83115. if (this._staticDefines.indexOf("DOF") != -1) {
  83116. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  83117. varyingCount--;
  83118. }
  83119. for (var i = 0; i < varyingCount; i++) {
  83120. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  83121. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  83122. }
  83123. var depCount = 0;
  83124. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  83125. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  83126. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  83127. depCount++;
  83128. }
  83129. if (this.packedFloat) {
  83130. defines += "#define PACKEDFLOAT 1";
  83131. }
  83132. this.blockCompilation = false;
  83133. _super.prototype.updateEffect.call(this, defines, null, null, {
  83134. varyingCount: varyingCount,
  83135. depCount: depCount
  83136. }, onCompiled, onError);
  83137. };
  83138. /**
  83139. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  83140. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  83141. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  83142. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  83143. * The gaps between physical kernels are compensated for in the weighting of the samples
  83144. * @param idealKernel Ideal blur kernel.
  83145. * @return Nearest best kernel.
  83146. */
  83147. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  83148. var v = Math.round(idealKernel);
  83149. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  83150. var k = _a[_i];
  83151. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  83152. return Math.max(k, 3);
  83153. }
  83154. }
  83155. return Math.max(v, 3);
  83156. };
  83157. /**
  83158. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  83159. * @param x The point on the Gaussian distribution to sample.
  83160. * @return the value of the Gaussian function at x.
  83161. */
  83162. BlurPostProcess.prototype._gaussianWeight = function (x) {
  83163. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  83164. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  83165. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  83166. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  83167. // truncated at around 1.3% of peak strength.
  83168. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  83169. var sigma = (1 / 3);
  83170. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  83171. var exponent = -((x * x) / (2.0 * sigma * sigma));
  83172. var weight = (1.0 / denominator) * Math.exp(exponent);
  83173. return weight;
  83174. };
  83175. /**
  83176. * Generates a string that can be used as a floating point number in GLSL.
  83177. * @param x Value to print.
  83178. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  83179. * @return GLSL float string.
  83180. */
  83181. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  83182. if (decimalFigures === void 0) { decimalFigures = 8; }
  83183. return x.toFixed(decimalFigures).replace(/0+$/, '');
  83184. };
  83185. return BlurPostProcess;
  83186. }(BABYLON.PostProcess));
  83187. BABYLON.BlurPostProcess = BlurPostProcess;
  83188. })(BABYLON || (BABYLON = {}));
  83189. //# sourceMappingURL=babylon.blurPostProcess.js.map
  83190. var BABYLON;
  83191. (function (BABYLON) {
  83192. /**
  83193. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  83194. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  83195. * based on samples that have a large difference in distance than the center pixel.
  83196. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83197. */
  83198. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  83199. __extends(DepthOfFieldBlurPostProcess, _super);
  83200. /**
  83201. * Creates a new instance CircleOfConfusionPostProcess
  83202. * @param name The name of the effect.
  83203. * @param scene The scene the effect belongs to.
  83204. * @param direction The direction the blur should be applied.
  83205. * @param kernel The size of the kernel used to blur.
  83206. * @param options The required width/height ratio to downsize to before computing the render pass.
  83207. * @param camera The camera to apply the render pass to.
  83208. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  83209. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  83210. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83211. * @param engine The engine which the post process will be applied. (default: current engine)
  83212. * @param reusable If the post process can be reused on the same frame. (default: false)
  83213. * @param textureType Type of textures used when performing the post process. (default: 0)
  83214. * @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)
  83215. */
  83216. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  83217. if (imageToBlur === void 0) { imageToBlur = null; }
  83218. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83219. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83220. if (blockCompilation === void 0) { blockCompilation = false; }
  83221. 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;
  83222. _this.direction = direction;
  83223. _this.onApplyObservable.add(function (effect) {
  83224. if (imageToBlur != null) {
  83225. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  83226. }
  83227. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83228. if (scene.activeCamera) {
  83229. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83230. }
  83231. });
  83232. return _this;
  83233. }
  83234. return DepthOfFieldBlurPostProcess;
  83235. }(BABYLON.BlurPostProcess));
  83236. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  83237. })(BABYLON || (BABYLON = {}));
  83238. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  83239. var BABYLON;
  83240. (function (BABYLON) {
  83241. /**
  83242. * Options to be set when merging outputs from the default pipeline.
  83243. */
  83244. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  83245. function DepthOfFieldMergePostProcessOptions() {
  83246. }
  83247. return DepthOfFieldMergePostProcessOptions;
  83248. }());
  83249. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  83250. /**
  83251. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83252. */
  83253. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  83254. __extends(DepthOfFieldMergePostProcess, _super);
  83255. /**
  83256. * Creates a new instance of DepthOfFieldMergePostProcess
  83257. * @param name The name of the effect.
  83258. * @param originalFromInput Post process which's input will be used for the merge.
  83259. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  83260. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  83261. * @param options The required width/height ratio to downsize to before computing the render pass.
  83262. * @param camera The camera to apply the render pass to.
  83263. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83264. * @param engine The engine which the post process will be applied. (default: current engine)
  83265. * @param reusable If the post process can be reused on the same frame. (default: false)
  83266. * @param textureType Type of textures used when performing the post process. (default: 0)
  83267. * @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)
  83268. */
  83269. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83270. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83271. if (blockCompilation === void 0) { blockCompilation = false; }
  83272. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83273. _this.blurSteps = blurSteps;
  83274. _this.onApplyObservable.add(function (effect) {
  83275. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83276. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83277. blurSteps.forEach(function (step, index) {
  83278. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  83279. });
  83280. });
  83281. if (!blockCompilation) {
  83282. _this.updateEffect();
  83283. }
  83284. return _this;
  83285. }
  83286. /**
  83287. * Updates the effect with the current post process compile time values and recompiles the shader.
  83288. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83289. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83290. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83291. * @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
  83292. * @param onCompiled Called when the shader has been compiled.
  83293. * @param onError Called if there is an error when compiling a shader.
  83294. */
  83295. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83296. if (defines === void 0) { defines = null; }
  83297. if (uniforms === void 0) { uniforms = null; }
  83298. if (samplers === void 0) { samplers = null; }
  83299. if (!defines) {
  83300. defines = "";
  83301. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  83302. }
  83303. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  83304. };
  83305. return DepthOfFieldMergePostProcess;
  83306. }(BABYLON.PostProcess));
  83307. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  83308. })(BABYLON || (BABYLON = {}));
  83309. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  83310. var BABYLON;
  83311. (function (BABYLON) {
  83312. /**
  83313. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  83314. */
  83315. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  83316. __extends(CircleOfConfusionPostProcess, _super);
  83317. /**
  83318. * Creates a new instance CircleOfConfusionPostProcess
  83319. * @param name The name of the effect.
  83320. * @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.
  83321. * @param options The required width/height ratio to downsize to before computing the render pass.
  83322. * @param camera The camera to apply the render pass to.
  83323. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83324. * @param engine The engine which the post process will be applied. (default: current engine)
  83325. * @param reusable If the post process can be reused on the same frame. (default: false)
  83326. * @param textureType Type of textures used when performing the post process. (default: 0)
  83327. * @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)
  83328. */
  83329. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83331. if (blockCompilation === void 0) { blockCompilation = false; }
  83332. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83333. /**
  83334. * 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.
  83335. */
  83336. _this.lensSize = 50;
  83337. /**
  83338. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83339. */
  83340. _this.fStop = 1.4;
  83341. /**
  83342. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83343. */
  83344. _this.focusDistance = 2000;
  83345. /**
  83346. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  83347. */
  83348. _this.focalLength = 50;
  83349. _this._depthTexture = null;
  83350. _this._depthTexture = depthTexture;
  83351. _this.onApplyObservable.add(function (effect) {
  83352. if (!_this._depthTexture) {
  83353. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  83354. return;
  83355. }
  83356. effect.setTexture("depthSampler", _this._depthTexture);
  83357. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  83358. var aperture = _this.lensSize / _this.fStop;
  83359. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  83360. effect.setFloat('focusDistance', _this.focusDistance);
  83361. effect.setFloat('cocPrecalculation', cocPrecalculation);
  83362. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  83363. });
  83364. return _this;
  83365. }
  83366. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  83367. /**
  83368. * 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.
  83369. */
  83370. set: function (value) {
  83371. this._depthTexture = value;
  83372. },
  83373. enumerable: true,
  83374. configurable: true
  83375. });
  83376. return CircleOfConfusionPostProcess;
  83377. }(BABYLON.PostProcess));
  83378. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  83379. })(BABYLON || (BABYLON = {}));
  83380. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  83381. var BABYLON;
  83382. (function (BABYLON) {
  83383. /**
  83384. * Specifies the level of max blur that should be applied when using the depth of field effect
  83385. */
  83386. var DepthOfFieldEffectBlurLevel;
  83387. (function (DepthOfFieldEffectBlurLevel) {
  83388. /**
  83389. * Subtle blur
  83390. */
  83391. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  83392. /**
  83393. * Medium blur
  83394. */
  83395. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  83396. /**
  83397. * Large blur
  83398. */
  83399. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  83400. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  83401. ;
  83402. /**
  83403. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  83404. */
  83405. var DepthOfFieldEffect = /** @class */ (function (_super) {
  83406. __extends(DepthOfFieldEffect, _super);
  83407. /**
  83408. * Creates a new instance DepthOfFieldEffect
  83409. * @param scene The scene the effect belongs to.
  83410. * @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.
  83411. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83412. * @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)
  83413. */
  83414. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  83415. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  83416. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83417. if (blockCompilation === void 0) { blockCompilation = false; }
  83418. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  83419. return _this._effects;
  83420. }, true) || this;
  83421. /**
  83422. * @hidden Internal post processes in depth of field effect
  83423. */
  83424. _this._effects = [];
  83425. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  83426. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83427. // 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)
  83428. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  83429. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83430. _this._depthOfFieldBlurY = [];
  83431. _this._depthOfFieldBlurX = [];
  83432. var blurCount = 1;
  83433. var kernelSize = 15;
  83434. switch (blurLevel) {
  83435. case DepthOfFieldEffectBlurLevel.High: {
  83436. blurCount = 3;
  83437. kernelSize = 51;
  83438. break;
  83439. }
  83440. case DepthOfFieldEffectBlurLevel.Medium: {
  83441. blurCount = 2;
  83442. kernelSize = 31;
  83443. break;
  83444. }
  83445. default: {
  83446. kernelSize = 15;
  83447. blurCount = 1;
  83448. break;
  83449. }
  83450. }
  83451. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  83452. var ratio = 1.0;
  83453. for (var i = 0; i < blurCount; i++) {
  83454. 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);
  83455. blurY.autoClear = false;
  83456. ratio = 0.75 / Math.pow(2, i);
  83457. 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);
  83458. blurX.autoClear = false;
  83459. _this._depthOfFieldBlurY.push(blurY);
  83460. _this._depthOfFieldBlurX.push(blurX);
  83461. }
  83462. // Set all post processes on the effect.
  83463. _this._effects = [_this._circleOfConfusion];
  83464. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  83465. _this._effects.push(_this._depthOfFieldBlurY[i]);
  83466. _this._effects.push(_this._depthOfFieldBlurX[i]);
  83467. }
  83468. // Merge blurred images with original image based on circleOfConfusion
  83469. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83470. _this._dofMerge.autoClear = false;
  83471. _this._effects.push(_this._dofMerge);
  83472. return _this;
  83473. }
  83474. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  83475. get: function () {
  83476. return this._circleOfConfusion.focalLength;
  83477. },
  83478. /**
  83479. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  83480. */
  83481. set: function (value) {
  83482. this._circleOfConfusion.focalLength = value;
  83483. },
  83484. enumerable: true,
  83485. configurable: true
  83486. });
  83487. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  83488. get: function () {
  83489. return this._circleOfConfusion.fStop;
  83490. },
  83491. /**
  83492. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83493. */
  83494. set: function (value) {
  83495. this._circleOfConfusion.fStop = value;
  83496. },
  83497. enumerable: true,
  83498. configurable: true
  83499. });
  83500. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  83501. get: function () {
  83502. return this._circleOfConfusion.focusDistance;
  83503. },
  83504. /**
  83505. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83506. */
  83507. set: function (value) {
  83508. this._circleOfConfusion.focusDistance = value;
  83509. },
  83510. enumerable: true,
  83511. configurable: true
  83512. });
  83513. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83514. get: function () {
  83515. return this._circleOfConfusion.lensSize;
  83516. },
  83517. /**
  83518. * 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.
  83519. */
  83520. set: function (value) {
  83521. this._circleOfConfusion.lensSize = value;
  83522. },
  83523. enumerable: true,
  83524. configurable: true
  83525. });
  83526. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83527. /**
  83528. * 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.
  83529. */
  83530. set: function (value) {
  83531. this._circleOfConfusion.depthTexture = value;
  83532. },
  83533. enumerable: true,
  83534. configurable: true
  83535. });
  83536. /**
  83537. * Disposes each of the internal effects for a given camera.
  83538. * @param camera The camera to dispose the effect on.
  83539. */
  83540. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83541. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83542. this._effects[effectIndex].dispose(camera);
  83543. }
  83544. };
  83545. /**
  83546. * @hidden Internal
  83547. */
  83548. DepthOfFieldEffect.prototype._updateEffects = function () {
  83549. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83550. this._effects[effectIndex].updateEffect();
  83551. }
  83552. };
  83553. /**
  83554. * Internal
  83555. * @returns if all the contained post processes are ready.
  83556. * @hidden
  83557. */
  83558. DepthOfFieldEffect.prototype._isReady = function () {
  83559. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83560. if (!this._effects[effectIndex].isReady()) {
  83561. return false;
  83562. }
  83563. }
  83564. return true;
  83565. };
  83566. return DepthOfFieldEffect;
  83567. }(BABYLON.PostProcessRenderEffect));
  83568. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83569. })(BABYLON || (BABYLON = {}));
  83570. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83571. var BABYLON;
  83572. (function (BABYLON) {
  83573. /**
  83574. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83575. */
  83576. var BloomMergePostProcess = /** @class */ (function (_super) {
  83577. __extends(BloomMergePostProcess, _super);
  83578. /**
  83579. * Creates a new instance of @see BloomMergePostProcess
  83580. * @param name The name of the effect.
  83581. * @param originalFromInput Post process which's input will be used for the merge.
  83582. * @param blurred Blurred highlights post process which's output will be used.
  83583. * @param weight Weight of the bloom to be added to the original input.
  83584. * @param options The required width/height ratio to downsize to before computing the render pass.
  83585. * @param camera The camera to apply the render pass to.
  83586. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83587. * @param engine The engine which the post process will be applied. (default: current engine)
  83588. * @param reusable If the post process can be reused on the same frame. (default: false)
  83589. * @param textureType Type of textures used when performing the post process. (default: 0)
  83590. * @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)
  83591. */
  83592. function BloomMergePostProcess(name, originalFromInput, blurred,
  83593. /** Weight of the bloom to be added to the original input. */
  83594. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83596. if (blockCompilation === void 0) { blockCompilation = false; }
  83597. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83598. _this.weight = weight;
  83599. _this.onApplyObservable.add(function (effect) {
  83600. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83601. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83602. effect.setFloat("bloomWeight", _this.weight);
  83603. });
  83604. if (!blockCompilation) {
  83605. _this.updateEffect();
  83606. }
  83607. return _this;
  83608. }
  83609. return BloomMergePostProcess;
  83610. }(BABYLON.PostProcess));
  83611. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83612. })(BABYLON || (BABYLON = {}));
  83613. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83614. var BABYLON;
  83615. (function (BABYLON) {
  83616. /**
  83617. * 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.
  83618. */
  83619. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83620. __extends(ExtractHighlightsPostProcess, _super);
  83621. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83622. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83623. if (blockCompilation === void 0) { blockCompilation = false; }
  83624. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83625. /**
  83626. * The luminance threshold, pixels below this value will be set to black.
  83627. */
  83628. _this.threshold = 0.9;
  83629. /** @hidden */
  83630. _this._exposure = 1;
  83631. /**
  83632. * Post process which has the input texture to be used when performing highlight extraction
  83633. * @hidden
  83634. */
  83635. _this._inputPostProcess = null;
  83636. _this.onApplyObservable.add(function (effect) {
  83637. if (_this._inputPostProcess) {
  83638. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  83639. }
  83640. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  83641. effect.setFloat('exposure', _this._exposure);
  83642. });
  83643. return _this;
  83644. }
  83645. return ExtractHighlightsPostProcess;
  83646. }(BABYLON.PostProcess));
  83647. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  83648. })(BABYLON || (BABYLON = {}));
  83649. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  83650. var BABYLON;
  83651. (function (BABYLON) {
  83652. /**
  83653. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  83654. */
  83655. var BloomEffect = /** @class */ (function (_super) {
  83656. __extends(BloomEffect, _super);
  83657. /**
  83658. * Creates a new instance of @see BloomEffect
  83659. * @param scene The scene the effect belongs to.
  83660. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  83661. * @param bloomKernel The size of the kernel to be used when applying the blur.
  83662. * @param bloomWeight The the strength of bloom.
  83663. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83664. * @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)
  83665. */
  83666. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  83667. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83668. if (blockCompilation === void 0) { blockCompilation = false; }
  83669. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  83670. return _this._effects;
  83671. }, true) || this;
  83672. _this.bloomScale = bloomScale;
  83673. /**
  83674. * @hidden Internal
  83675. */
  83676. _this._effects = [];
  83677. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83678. _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);
  83679. _this._blurX.alwaysForcePOT = true;
  83680. _this._blurX.autoClear = false;
  83681. _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);
  83682. _this._blurY.alwaysForcePOT = true;
  83683. _this._blurY.autoClear = false;
  83684. _this.kernel = bloomKernel;
  83685. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  83686. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83687. _this._merge.autoClear = false;
  83688. _this._effects.push(_this._merge);
  83689. return _this;
  83690. }
  83691. Object.defineProperty(BloomEffect.prototype, "threshold", {
  83692. /**
  83693. * The luminance threshold to find bright areas of the image to bloom.
  83694. */
  83695. get: function () {
  83696. return this._downscale.threshold;
  83697. },
  83698. set: function (value) {
  83699. this._downscale.threshold = value;
  83700. },
  83701. enumerable: true,
  83702. configurable: true
  83703. });
  83704. Object.defineProperty(BloomEffect.prototype, "weight", {
  83705. /**
  83706. * The strength of the bloom.
  83707. */
  83708. get: function () {
  83709. return this._merge.weight;
  83710. },
  83711. set: function (value) {
  83712. this._merge.weight = value;
  83713. },
  83714. enumerable: true,
  83715. configurable: true
  83716. });
  83717. Object.defineProperty(BloomEffect.prototype, "kernel", {
  83718. /**
  83719. * Specifies the size of the bloom blur kernel, relative to the final output size
  83720. */
  83721. get: function () {
  83722. return this._blurX.kernel / this.bloomScale;
  83723. },
  83724. set: function (value) {
  83725. this._blurX.kernel = value * this.bloomScale;
  83726. this._blurY.kernel = value * this.bloomScale;
  83727. },
  83728. enumerable: true,
  83729. configurable: true
  83730. });
  83731. /**
  83732. * Disposes each of the internal effects for a given camera.
  83733. * @param camera The camera to dispose the effect on.
  83734. */
  83735. BloomEffect.prototype.disposeEffects = function (camera) {
  83736. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83737. this._effects[effectIndex].dispose(camera);
  83738. }
  83739. };
  83740. /**
  83741. * @hidden Internal
  83742. */
  83743. BloomEffect.prototype._updateEffects = function () {
  83744. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83745. this._effects[effectIndex].updateEffect();
  83746. }
  83747. };
  83748. /**
  83749. * Internal
  83750. * @returns if all the contained post processes are ready.
  83751. * @hidden
  83752. */
  83753. BloomEffect.prototype._isReady = function () {
  83754. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83755. if (!this._effects[effectIndex].isReady()) {
  83756. return false;
  83757. }
  83758. }
  83759. return true;
  83760. };
  83761. return BloomEffect;
  83762. }(BABYLON.PostProcessRenderEffect));
  83763. BABYLON.BloomEffect = BloomEffect;
  83764. })(BABYLON || (BABYLON = {}));
  83765. //# sourceMappingURL=babylon.bloomEffect.js.map
  83766. var BABYLON;
  83767. (function (BABYLON) {
  83768. /**
  83769. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  83770. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  83771. */
  83772. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  83773. __extends(DefaultRenderingPipeline, _super);
  83774. /**
  83775. * @constructor
  83776. * @param {string} name - The rendering pipeline name (default: "")
  83777. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  83778. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  83779. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  83780. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  83781. */
  83782. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  83783. if (name === void 0) { name = ""; }
  83784. if (hdr === void 0) { hdr = true; }
  83785. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  83786. if (automaticBuild === void 0) { automaticBuild = true; }
  83787. var _this = _super.call(this, scene.getEngine(), name) || this;
  83788. _this._camerasToBeAttached = [];
  83789. /**
  83790. * ID of the sharpen post process,
  83791. */
  83792. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  83793. /**
  83794. * ID of the image processing post process;
  83795. */
  83796. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  83797. /**
  83798. * ID of the Fast Approximate Anti-Aliasing post process;
  83799. */
  83800. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  83801. /**
  83802. * ID of the chromatic aberration post process,
  83803. */
  83804. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  83805. /**
  83806. * ID of the grain post process
  83807. */
  83808. _this.GrainPostProcessId = "GrainPostProcessEffect";
  83809. /**
  83810. * Glow post process which adds a glow to emmisive areas of the image
  83811. */
  83812. _this._glowLayer = null;
  83813. /**
  83814. * Animations which can be used to tweak settings over a period of time
  83815. */
  83816. _this.animations = [];
  83817. _this._imageProcessingConfigurationObserver = null;
  83818. // Values
  83819. _this._sharpenEnabled = false;
  83820. _this._bloomEnabled = false;
  83821. _this._depthOfFieldEnabled = false;
  83822. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  83823. _this._fxaaEnabled = false;
  83824. _this._imageProcessingEnabled = true;
  83825. _this._bloomScale = 0.5;
  83826. _this._chromaticAberrationEnabled = false;
  83827. _this._grainEnabled = false;
  83828. _this._buildAllowed = true;
  83829. _this._resizeObserver = null;
  83830. _this._hardwareScaleLevel = 1.0;
  83831. _this._bloomKernel = 64;
  83832. /**
  83833. * Specifies the weight of the bloom in the final rendering
  83834. */
  83835. _this._bloomWeight = 0.15;
  83836. /**
  83837. * Specifies the luma threshold for the area that will be blurred by the bloom
  83838. */
  83839. _this._bloomThreshold = 0.9;
  83840. _this._samples = 1;
  83841. _this._hasCleared = false;
  83842. _this._prevPostProcess = null;
  83843. _this._prevPrevPostProcess = null;
  83844. _this._depthOfFieldSceneObserver = null;
  83845. _this._cameras = cameras || scene.cameras;
  83846. _this._cameras = _this._cameras.slice();
  83847. _this._camerasToBeAttached = _this._cameras.slice();
  83848. _this._buildAllowed = automaticBuild;
  83849. // Initialize
  83850. _this._scene = scene;
  83851. var caps = _this._scene.getEngine().getCaps();
  83852. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  83853. // Misc
  83854. if (_this._hdr) {
  83855. if (caps.textureHalfFloatRender) {
  83856. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83857. }
  83858. else if (caps.textureFloatRender) {
  83859. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83860. }
  83861. }
  83862. else {
  83863. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83864. }
  83865. // Attach
  83866. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83867. var engine = _this._scene.getEngine();
  83868. // Create post processes before hand so they can be modified before enabled.
  83869. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  83870. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83871. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  83872. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  83873. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  83874. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83875. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  83876. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83877. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  83878. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83879. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83880. _this.bloomKernel = _this.bloomKernel;
  83881. });
  83882. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83883. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83884. });
  83885. _this._buildPipeline();
  83886. return _this;
  83887. }
  83888. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83889. get: function () {
  83890. return this._sharpenEnabled;
  83891. },
  83892. /**
  83893. * Enable or disable the sharpen process from the pipeline
  83894. */
  83895. set: function (enabled) {
  83896. if (this._sharpenEnabled === enabled) {
  83897. return;
  83898. }
  83899. this._sharpenEnabled = enabled;
  83900. this._buildPipeline();
  83901. },
  83902. enumerable: true,
  83903. configurable: true
  83904. });
  83905. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83906. /**
  83907. * Specifies the size of the bloom blur kernel, relative to the final output size
  83908. */
  83909. get: function () {
  83910. return this._bloomKernel;
  83911. },
  83912. set: function (value) {
  83913. this._bloomKernel = value;
  83914. this.bloom.kernel = value / this._hardwareScaleLevel;
  83915. },
  83916. enumerable: true,
  83917. configurable: true
  83918. });
  83919. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83920. get: function () {
  83921. return this._bloomWeight;
  83922. },
  83923. /**
  83924. * The strength of the bloom.
  83925. */
  83926. set: function (value) {
  83927. if (this._bloomWeight === value) {
  83928. return;
  83929. }
  83930. this.bloom.weight = value;
  83931. this._bloomWeight = value;
  83932. },
  83933. enumerable: true,
  83934. configurable: true
  83935. });
  83936. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83937. get: function () {
  83938. return this._bloomThreshold;
  83939. },
  83940. /**
  83941. * The strength of the bloom.
  83942. */
  83943. set: function (value) {
  83944. if (this._bloomThreshold === value) {
  83945. return;
  83946. }
  83947. this.bloom.threshold = value;
  83948. this._bloomThreshold = value;
  83949. },
  83950. enumerable: true,
  83951. configurable: true
  83952. });
  83953. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83954. get: function () {
  83955. return this._bloomScale;
  83956. },
  83957. /**
  83958. * The scale of the bloom, lower value will provide better performance.
  83959. */
  83960. set: function (value) {
  83961. if (this._bloomScale === value) {
  83962. return;
  83963. }
  83964. this._bloomScale = value;
  83965. // recreate bloom and dispose old as this setting is not dynamic
  83966. this._rebuildBloom();
  83967. this._buildPipeline();
  83968. },
  83969. enumerable: true,
  83970. configurable: true
  83971. });
  83972. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83973. get: function () {
  83974. return this._bloomEnabled;
  83975. },
  83976. /**
  83977. * Enable or disable the bloom from the pipeline
  83978. */
  83979. set: function (enabled) {
  83980. if (this._bloomEnabled === enabled) {
  83981. return;
  83982. }
  83983. this._bloomEnabled = enabled;
  83984. this._buildPipeline();
  83985. },
  83986. enumerable: true,
  83987. configurable: true
  83988. });
  83989. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  83990. // recreate bloom and dispose old as this setting is not dynamic
  83991. var oldBloom = this.bloom;
  83992. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  83993. this.bloom.threshold = oldBloom.threshold;
  83994. for (var i = 0; i < this._cameras.length; i++) {
  83995. oldBloom.disposeEffects(this._cameras[i]);
  83996. }
  83997. };
  83998. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  83999. /**
  84000. * If the depth of field is enabled.
  84001. */
  84002. get: function () {
  84003. return this._depthOfFieldEnabled;
  84004. },
  84005. set: function (enabled) {
  84006. if (this._depthOfFieldEnabled === enabled) {
  84007. return;
  84008. }
  84009. this._depthOfFieldEnabled = enabled;
  84010. this._buildPipeline();
  84011. },
  84012. enumerable: true,
  84013. configurable: true
  84014. });
  84015. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  84016. /**
  84017. * Blur level of the depth of field effect. (Higher blur will effect performance)
  84018. */
  84019. get: function () {
  84020. return this._depthOfFieldBlurLevel;
  84021. },
  84022. set: function (value) {
  84023. if (this._depthOfFieldBlurLevel === value) {
  84024. return;
  84025. }
  84026. this._depthOfFieldBlurLevel = value;
  84027. // recreate dof and dispose old as this setting is not dynamic
  84028. var oldDof = this.depthOfField;
  84029. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  84030. this.depthOfField.focalLength = oldDof.focalLength;
  84031. this.depthOfField.focusDistance = oldDof.focusDistance;
  84032. this.depthOfField.fStop = oldDof.fStop;
  84033. this.depthOfField.lensSize = oldDof.lensSize;
  84034. for (var i = 0; i < this._cameras.length; i++) {
  84035. oldDof.disposeEffects(this._cameras[i]);
  84036. }
  84037. this._buildPipeline();
  84038. },
  84039. enumerable: true,
  84040. configurable: true
  84041. });
  84042. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  84043. get: function () {
  84044. return this._fxaaEnabled;
  84045. },
  84046. /**
  84047. * If the anti aliasing is enabled.
  84048. */
  84049. set: function (enabled) {
  84050. if (this._fxaaEnabled === enabled) {
  84051. return;
  84052. }
  84053. this._fxaaEnabled = enabled;
  84054. this._buildPipeline();
  84055. },
  84056. enumerable: true,
  84057. configurable: true
  84058. });
  84059. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  84060. get: function () {
  84061. return this._samples;
  84062. },
  84063. /**
  84064. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84065. */
  84066. set: function (sampleCount) {
  84067. if (this._samples === sampleCount) {
  84068. return;
  84069. }
  84070. this._samples = sampleCount;
  84071. this._buildPipeline();
  84072. },
  84073. enumerable: true,
  84074. configurable: true
  84075. });
  84076. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  84077. get: function () {
  84078. return this._imageProcessingEnabled;
  84079. },
  84080. /**
  84081. * If image processing is enabled.
  84082. */
  84083. set: function (enabled) {
  84084. if (this._imageProcessingEnabled === enabled) {
  84085. return;
  84086. }
  84087. this._imageProcessingEnabled = enabled;
  84088. this._buildPipeline();
  84089. },
  84090. enumerable: true,
  84091. configurable: true
  84092. });
  84093. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  84094. get: function () {
  84095. return this._glowLayer == null;
  84096. },
  84097. /**
  84098. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  84099. */
  84100. set: function (enabled) {
  84101. if (enabled && !this._glowLayer) {
  84102. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  84103. }
  84104. else if (!enabled && this._glowLayer) {
  84105. this._glowLayer.dispose();
  84106. this._glowLayer = null;
  84107. }
  84108. },
  84109. enumerable: true,
  84110. configurable: true
  84111. });
  84112. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  84113. get: function () {
  84114. return this._chromaticAberrationEnabled;
  84115. },
  84116. /**
  84117. * Enable or disable the chromaticAberration process from the pipeline
  84118. */
  84119. set: function (enabled) {
  84120. if (this._chromaticAberrationEnabled === enabled) {
  84121. return;
  84122. }
  84123. this._chromaticAberrationEnabled = enabled;
  84124. this._buildPipeline();
  84125. },
  84126. enumerable: true,
  84127. configurable: true
  84128. });
  84129. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  84130. get: function () {
  84131. return this._grainEnabled;
  84132. },
  84133. /**
  84134. * Enable or disable the grain process from the pipeline
  84135. */
  84136. set: function (enabled) {
  84137. if (this._grainEnabled === enabled) {
  84138. return;
  84139. }
  84140. this._grainEnabled = enabled;
  84141. this._buildPipeline();
  84142. },
  84143. enumerable: true,
  84144. configurable: true
  84145. });
  84146. /**
  84147. * Force the compilation of the entire pipeline.
  84148. */
  84149. DefaultRenderingPipeline.prototype.prepare = function () {
  84150. var previousState = this._buildAllowed;
  84151. this._buildAllowed = true;
  84152. this._buildPipeline();
  84153. this._buildAllowed = previousState;
  84154. };
  84155. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  84156. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  84157. if (this._hasCleared) {
  84158. postProcess.autoClear = false;
  84159. }
  84160. else {
  84161. postProcess.autoClear = true;
  84162. this._scene.autoClear = false;
  84163. this._hasCleared = true;
  84164. }
  84165. if (!skipTextureSharing) {
  84166. if (this._prevPrevPostProcess) {
  84167. postProcess.shareOutputWith(this._prevPrevPostProcess);
  84168. }
  84169. else {
  84170. postProcess.useOwnOutput();
  84171. }
  84172. if (this._prevPostProcess) {
  84173. this._prevPrevPostProcess = this._prevPostProcess;
  84174. }
  84175. this._prevPostProcess = postProcess;
  84176. }
  84177. };
  84178. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  84179. var _this = this;
  84180. if (!this._buildAllowed) {
  84181. return;
  84182. }
  84183. this._scene.autoClear = true;
  84184. var engine = this._scene.getEngine();
  84185. this._disposePostProcesses();
  84186. if (this._cameras !== null) {
  84187. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84188. // get back cameras to be used to reattach pipeline
  84189. this._cameras = this._camerasToBeAttached.slice();
  84190. }
  84191. this._reset();
  84192. this._prevPostProcess = null;
  84193. this._prevPrevPostProcess = null;
  84194. this._hasCleared = false;
  84195. if (this.depthOfFieldEnabled) {
  84196. // Multi camera suport
  84197. if (this._cameras.length > 1) {
  84198. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  84199. var camera = _a[_i];
  84200. var depthRenderer = this._scene.enableDepthRenderer(camera);
  84201. depthRenderer.useOnlyInActiveCamera = true;
  84202. }
  84203. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  84204. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  84205. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  84206. }
  84207. });
  84208. }
  84209. else {
  84210. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84211. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  84212. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  84213. }
  84214. if (!this.depthOfField._isReady()) {
  84215. this.depthOfField._updateEffects();
  84216. }
  84217. this.addEffect(this.depthOfField);
  84218. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  84219. }
  84220. else {
  84221. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84222. }
  84223. if (this.bloomEnabled) {
  84224. if (!this.bloom._isReady()) {
  84225. this.bloom._updateEffects();
  84226. }
  84227. this.addEffect(this.bloom);
  84228. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  84229. }
  84230. if (this._imageProcessingEnabled) {
  84231. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84232. if (this._hdr) {
  84233. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  84234. this._setAutoClearAndTextureSharing(this.imageProcessing);
  84235. }
  84236. else {
  84237. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  84238. }
  84239. }
  84240. if (this.sharpenEnabled) {
  84241. if (!this.sharpen.isReady()) {
  84242. this.sharpen.updateEffect();
  84243. }
  84244. this.addEffect(this._sharpenEffect);
  84245. this._setAutoClearAndTextureSharing(this.sharpen);
  84246. }
  84247. if (this.grainEnabled) {
  84248. if (!this.grain.isReady()) {
  84249. this.grain.updateEffect();
  84250. }
  84251. this.addEffect(this._grainEffect);
  84252. this._setAutoClearAndTextureSharing(this.grain);
  84253. }
  84254. if (this.chromaticAberrationEnabled) {
  84255. if (!this.chromaticAberration.isReady()) {
  84256. this.chromaticAberration.updateEffect();
  84257. }
  84258. this.addEffect(this._chromaticAberrationEffect);
  84259. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  84260. }
  84261. if (this.fxaaEnabled) {
  84262. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84263. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  84264. this._setAutoClearAndTextureSharing(this.fxaa, true);
  84265. }
  84266. if (this._cameras !== null) {
  84267. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84268. }
  84269. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  84270. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84271. }
  84272. };
  84273. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  84274. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  84275. for (var i = 0; i < this._cameras.length; i++) {
  84276. var camera = this._cameras[i];
  84277. if (this.imageProcessing) {
  84278. this.imageProcessing.dispose(camera);
  84279. }
  84280. if (this.fxaa) {
  84281. this.fxaa.dispose(camera);
  84282. }
  84283. // These are created in the constructor and should not be disposed on every pipeline change
  84284. if (disposeNonRecreated) {
  84285. if (this.sharpen) {
  84286. this.sharpen.dispose(camera);
  84287. }
  84288. if (this.depthOfField) {
  84289. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84290. this.depthOfField.disposeEffects(camera);
  84291. }
  84292. if (this.bloom) {
  84293. this.bloom.disposeEffects(camera);
  84294. }
  84295. if (this.chromaticAberration) {
  84296. this.chromaticAberration.dispose(camera);
  84297. }
  84298. if (this.grain) {
  84299. this.grain.dispose(camera);
  84300. }
  84301. if (this._glowLayer) {
  84302. this._glowLayer.dispose();
  84303. }
  84304. }
  84305. }
  84306. this.imageProcessing = null;
  84307. this.fxaa = null;
  84308. if (disposeNonRecreated) {
  84309. this.sharpen = null;
  84310. this._sharpenEffect = null;
  84311. this.depthOfField = null;
  84312. this.bloom = null;
  84313. this.chromaticAberration = null;
  84314. this._chromaticAberrationEffect = null;
  84315. this.grain = null;
  84316. this._grainEffect = null;
  84317. this._glowLayer = null;
  84318. }
  84319. };
  84320. /**
  84321. * Adds a camera to the pipeline
  84322. * @param camera the camera to be added
  84323. */
  84324. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  84325. this._camerasToBeAttached.push(camera);
  84326. this._buildPipeline();
  84327. };
  84328. /**
  84329. * Removes a camera from the pipeline
  84330. * @param camera the camera to remove
  84331. */
  84332. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  84333. var index = this._camerasToBeAttached.indexOf(camera);
  84334. this._camerasToBeAttached.splice(index, 1);
  84335. this._buildPipeline();
  84336. };
  84337. /**
  84338. * Dispose of the pipeline and stop all post processes
  84339. */
  84340. DefaultRenderingPipeline.prototype.dispose = function () {
  84341. this._disposePostProcesses(true);
  84342. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84343. this._scene.autoClear = true;
  84344. if (this._resizeObserver) {
  84345. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  84346. this._resizeObserver = null;
  84347. }
  84348. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  84349. _super.prototype.dispose.call(this);
  84350. };
  84351. /**
  84352. * Serialize the rendering pipeline (Used when exporting)
  84353. * @returns the serialized object
  84354. */
  84355. DefaultRenderingPipeline.prototype.serialize = function () {
  84356. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84357. serializationObject.customType = "DefaultRenderingPipeline";
  84358. return serializationObject;
  84359. };
  84360. /**
  84361. * Parse the serialized pipeline
  84362. * @param source Source pipeline.
  84363. * @param scene The scene to load the pipeline to.
  84364. * @param rootUrl The URL of the serialized pipeline.
  84365. * @returns An instantiated pipeline from the serialized object.
  84366. */
  84367. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84368. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  84369. };
  84370. __decorate([
  84371. BABYLON.serialize()
  84372. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  84373. __decorate([
  84374. BABYLON.serialize()
  84375. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  84376. __decorate([
  84377. BABYLON.serialize()
  84378. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  84379. __decorate([
  84380. BABYLON.serialize()
  84381. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  84382. __decorate([
  84383. BABYLON.serialize()
  84384. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  84385. __decorate([
  84386. BABYLON.serialize()
  84387. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  84388. __decorate([
  84389. BABYLON.serialize()
  84390. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  84391. __decorate([
  84392. BABYLON.serialize()
  84393. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  84394. __decorate([
  84395. BABYLON.serialize()
  84396. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  84397. __decorate([
  84398. BABYLON.serialize()
  84399. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  84400. __decorate([
  84401. BABYLON.serialize()
  84402. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  84403. __decorate([
  84404. BABYLON.serialize()
  84405. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  84406. __decorate([
  84407. BABYLON.serialize()
  84408. ], DefaultRenderingPipeline.prototype, "samples", null);
  84409. __decorate([
  84410. BABYLON.serialize()
  84411. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  84412. __decorate([
  84413. BABYLON.serialize()
  84414. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  84415. __decorate([
  84416. BABYLON.serialize()
  84417. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  84418. __decorate([
  84419. BABYLON.serialize()
  84420. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  84421. return DefaultRenderingPipeline;
  84422. }(BABYLON.PostProcessRenderPipeline));
  84423. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  84424. })(BABYLON || (BABYLON = {}));
  84425. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  84426. var BABYLON;
  84427. (function (BABYLON) {
  84428. /**
  84429. * @hidden
  84430. */
  84431. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  84432. __extends(ImageProcessingConfigurationDefines, _super);
  84433. function ImageProcessingConfigurationDefines() {
  84434. var _this = _super.call(this) || this;
  84435. _this.IMAGEPROCESSING = false;
  84436. _this.VIGNETTE = false;
  84437. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84438. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84439. _this.TONEMAPPING = false;
  84440. _this.TONEMAPPING_ACES = false;
  84441. _this.CONTRAST = false;
  84442. _this.COLORCURVES = false;
  84443. _this.COLORGRADING = false;
  84444. _this.COLORGRADING3D = false;
  84445. _this.SAMPLER3DGREENDEPTH = false;
  84446. _this.SAMPLER3DBGRMAP = false;
  84447. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84448. _this.EXPOSURE = false;
  84449. _this.rebuild();
  84450. return _this;
  84451. }
  84452. return ImageProcessingConfigurationDefines;
  84453. }(BABYLON.MaterialDefines));
  84454. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  84455. /**
  84456. * This groups together the common properties used for image processing either in direct forward pass
  84457. * or through post processing effect depending on the use of the image processing pipeline in your scene
  84458. * or not.
  84459. */
  84460. var ImageProcessingConfiguration = /** @class */ (function () {
  84461. function ImageProcessingConfiguration() {
  84462. /**
  84463. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  84464. */
  84465. this.colorCurves = new BABYLON.ColorCurves();
  84466. this._colorCurvesEnabled = false;
  84467. this._colorGradingEnabled = false;
  84468. this._colorGradingWithGreenDepth = true;
  84469. this._colorGradingBGR = true;
  84470. /** @hidden */
  84471. this._exposure = 1.0;
  84472. this._toneMappingEnabled = false;
  84473. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  84474. this._contrast = 1.0;
  84475. /**
  84476. * Vignette stretch size.
  84477. */
  84478. this.vignetteStretch = 0;
  84479. /**
  84480. * Vignette centre X Offset.
  84481. */
  84482. this.vignetteCentreX = 0;
  84483. /**
  84484. * Vignette centre Y Offset.
  84485. */
  84486. this.vignetteCentreY = 0;
  84487. /**
  84488. * Vignette weight or intensity of the vignette effect.
  84489. */
  84490. this.vignetteWeight = 1.5;
  84491. /**
  84492. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84493. * if vignetteEnabled is set to true.
  84494. */
  84495. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84496. /**
  84497. * Camera field of view used by the Vignette effect.
  84498. */
  84499. this.vignetteCameraFov = 0.5;
  84500. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  84501. this._vignetteEnabled = false;
  84502. this._applyByPostProcess = false;
  84503. this._isEnabled = true;
  84504. /**
  84505. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  84506. */
  84507. this.onUpdateParameters = new BABYLON.Observable();
  84508. }
  84509. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84510. /**
  84511. * Gets wether the color curves effect is enabled.
  84512. */
  84513. get: function () {
  84514. return this._colorCurvesEnabled;
  84515. },
  84516. /**
  84517. * Sets wether the color curves effect is enabled.
  84518. */
  84519. set: function (value) {
  84520. if (this._colorCurvesEnabled === value) {
  84521. return;
  84522. }
  84523. this._colorCurvesEnabled = value;
  84524. this._updateParameters();
  84525. },
  84526. enumerable: true,
  84527. configurable: true
  84528. });
  84529. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84530. /**
  84531. * Gets wether the color grading effect is enabled.
  84532. */
  84533. get: function () {
  84534. return this._colorGradingEnabled;
  84535. },
  84536. /**
  84537. * Sets wether the color grading effect is enabled.
  84538. */
  84539. set: function (value) {
  84540. if (this._colorGradingEnabled === value) {
  84541. return;
  84542. }
  84543. this._colorGradingEnabled = value;
  84544. this._updateParameters();
  84545. },
  84546. enumerable: true,
  84547. configurable: true
  84548. });
  84549. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84550. /**
  84551. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84552. */
  84553. get: function () {
  84554. return this._colorGradingWithGreenDepth;
  84555. },
  84556. /**
  84557. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84558. */
  84559. set: function (value) {
  84560. if (this._colorGradingWithGreenDepth === value) {
  84561. return;
  84562. }
  84563. this._colorGradingWithGreenDepth = value;
  84564. this._updateParameters();
  84565. },
  84566. enumerable: true,
  84567. configurable: true
  84568. });
  84569. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84570. /**
  84571. * Gets wether the color grading texture contains BGR values.
  84572. */
  84573. get: function () {
  84574. return this._colorGradingBGR;
  84575. },
  84576. /**
  84577. * Sets wether the color grading texture contains BGR values.
  84578. */
  84579. set: function (value) {
  84580. if (this._colorGradingBGR === value) {
  84581. return;
  84582. }
  84583. this._colorGradingBGR = value;
  84584. this._updateParameters();
  84585. },
  84586. enumerable: true,
  84587. configurable: true
  84588. });
  84589. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84590. /**
  84591. * Gets the Exposure used in the effect.
  84592. */
  84593. get: function () {
  84594. return this._exposure;
  84595. },
  84596. /**
  84597. * Sets the Exposure used in the effect.
  84598. */
  84599. set: function (value) {
  84600. if (this._exposure === value) {
  84601. return;
  84602. }
  84603. this._exposure = value;
  84604. this._updateParameters();
  84605. },
  84606. enumerable: true,
  84607. configurable: true
  84608. });
  84609. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84610. /**
  84611. * Gets wether the tone mapping effect is enabled.
  84612. */
  84613. get: function () {
  84614. return this._toneMappingEnabled;
  84615. },
  84616. /**
  84617. * Sets wether the tone mapping effect is enabled.
  84618. */
  84619. set: function (value) {
  84620. if (this._toneMappingEnabled === value) {
  84621. return;
  84622. }
  84623. this._toneMappingEnabled = value;
  84624. this._updateParameters();
  84625. },
  84626. enumerable: true,
  84627. configurable: true
  84628. });
  84629. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84630. /**
  84631. * Gets the type of tone mapping effect.
  84632. */
  84633. get: function () {
  84634. return this._toneMappingType;
  84635. },
  84636. /**
  84637. * Sets the type of tone mapping effect used in BabylonJS.
  84638. */
  84639. set: function (value) {
  84640. if (this._toneMappingType === value) {
  84641. return;
  84642. }
  84643. this._toneMappingType = value;
  84644. this._updateParameters();
  84645. },
  84646. enumerable: true,
  84647. configurable: true
  84648. });
  84649. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  84650. /**
  84651. * Gets the contrast used in the effect.
  84652. */
  84653. get: function () {
  84654. return this._contrast;
  84655. },
  84656. /**
  84657. * Sets the contrast used in the effect.
  84658. */
  84659. set: function (value) {
  84660. if (this._contrast === value) {
  84661. return;
  84662. }
  84663. this._contrast = value;
  84664. this._updateParameters();
  84665. },
  84666. enumerable: true,
  84667. configurable: true
  84668. });
  84669. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  84670. /**
  84671. * Gets the vignette blend mode allowing different kind of effect.
  84672. */
  84673. get: function () {
  84674. return this._vignetteBlendMode;
  84675. },
  84676. /**
  84677. * Sets the vignette blend mode allowing different kind of effect.
  84678. */
  84679. set: function (value) {
  84680. if (this._vignetteBlendMode === value) {
  84681. return;
  84682. }
  84683. this._vignetteBlendMode = value;
  84684. this._updateParameters();
  84685. },
  84686. enumerable: true,
  84687. configurable: true
  84688. });
  84689. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  84690. /**
  84691. * Gets wether the vignette effect is enabled.
  84692. */
  84693. get: function () {
  84694. return this._vignetteEnabled;
  84695. },
  84696. /**
  84697. * Sets wether the vignette effect is enabled.
  84698. */
  84699. set: function (value) {
  84700. if (this._vignetteEnabled === value) {
  84701. return;
  84702. }
  84703. this._vignetteEnabled = value;
  84704. this._updateParameters();
  84705. },
  84706. enumerable: true,
  84707. configurable: true
  84708. });
  84709. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  84710. /**
  84711. * Gets wether the image processing is applied through a post process or not.
  84712. */
  84713. get: function () {
  84714. return this._applyByPostProcess;
  84715. },
  84716. /**
  84717. * Sets wether the image processing is applied through a post process or not.
  84718. */
  84719. set: function (value) {
  84720. if (this._applyByPostProcess === value) {
  84721. return;
  84722. }
  84723. this._applyByPostProcess = value;
  84724. this._updateParameters();
  84725. },
  84726. enumerable: true,
  84727. configurable: true
  84728. });
  84729. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  84730. /**
  84731. * Gets wether the image processing is enabled or not.
  84732. */
  84733. get: function () {
  84734. return this._isEnabled;
  84735. },
  84736. /**
  84737. * Sets wether the image processing is enabled or not.
  84738. */
  84739. set: function (value) {
  84740. if (this._isEnabled === value) {
  84741. return;
  84742. }
  84743. this._isEnabled = value;
  84744. this._updateParameters();
  84745. },
  84746. enumerable: true,
  84747. configurable: true
  84748. });
  84749. /**
  84750. * Method called each time the image processing information changes requires to recompile the effect.
  84751. */
  84752. ImageProcessingConfiguration.prototype._updateParameters = function () {
  84753. this.onUpdateParameters.notifyObservers(this);
  84754. };
  84755. ImageProcessingConfiguration.prototype.getClassName = function () {
  84756. return "ImageProcessingConfiguration";
  84757. };
  84758. /**
  84759. * Prepare the list of uniforms associated with the Image Processing effects.
  84760. * @param uniformsList The list of uniforms used in the effect
  84761. * @param defines the list of defines currently in use
  84762. */
  84763. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  84764. if (defines.EXPOSURE) {
  84765. uniforms.push("exposureLinear");
  84766. }
  84767. if (defines.CONTRAST) {
  84768. uniforms.push("contrast");
  84769. }
  84770. if (defines.COLORGRADING) {
  84771. uniforms.push("colorTransformSettings");
  84772. }
  84773. if (defines.VIGNETTE) {
  84774. uniforms.push("vInverseScreenSize");
  84775. uniforms.push("vignetteSettings1");
  84776. uniforms.push("vignetteSettings2");
  84777. }
  84778. if (defines.COLORCURVES) {
  84779. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  84780. }
  84781. };
  84782. /**
  84783. * Prepare the list of samplers associated with the Image Processing effects.
  84784. * @param uniformsList The list of uniforms used in the effect
  84785. * @param defines the list of defines currently in use
  84786. */
  84787. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  84788. if (defines.COLORGRADING) {
  84789. samplersList.push("txColorTransform");
  84790. }
  84791. };
  84792. /**
  84793. * Prepare the list of defines associated to the shader.
  84794. * @param defines the list of defines to complete
  84795. */
  84796. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  84797. if (forPostProcess === void 0) { forPostProcess = false; }
  84798. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  84799. defines.VIGNETTE = false;
  84800. defines.TONEMAPPING = false;
  84801. defines.TONEMAPPING_ACES = false;
  84802. defines.CONTRAST = false;
  84803. defines.EXPOSURE = false;
  84804. defines.COLORCURVES = false;
  84805. defines.COLORGRADING = false;
  84806. defines.COLORGRADING3D = false;
  84807. defines.IMAGEPROCESSING = false;
  84808. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  84809. return;
  84810. }
  84811. defines.VIGNETTE = this.vignetteEnabled;
  84812. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  84813. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  84814. defines.TONEMAPPING = this.toneMappingEnabled;
  84815. switch (this._toneMappingType) {
  84816. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  84817. defines.TONEMAPPING_ACES = true;
  84818. break;
  84819. }
  84820. defines.CONTRAST = (this.contrast !== 1.0);
  84821. defines.EXPOSURE = (this.exposure !== 1.0);
  84822. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  84823. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  84824. if (defines.COLORGRADING) {
  84825. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  84826. }
  84827. else {
  84828. defines.COLORGRADING3D = false;
  84829. }
  84830. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  84831. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  84832. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  84833. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  84834. };
  84835. /**
  84836. * Returns true if all the image processing information are ready.
  84837. */
  84838. ImageProcessingConfiguration.prototype.isReady = function () {
  84839. // Color Grading texure can not be none blocking.
  84840. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  84841. };
  84842. /**
  84843. * Binds the image processing to the shader.
  84844. * @param effect The effect to bind to
  84845. */
  84846. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  84847. if (aspectRatio === void 0) { aspectRatio = 1; }
  84848. // Color Curves
  84849. if (this._colorCurvesEnabled && this.colorCurves) {
  84850. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  84851. }
  84852. // Vignette
  84853. if (this._vignetteEnabled) {
  84854. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  84855. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  84856. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  84857. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  84858. var vignetteScaleX = vignetteScaleY * aspectRatio;
  84859. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  84860. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  84861. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  84862. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  84863. var vignettePower = -2.0 * this.vignetteWeight;
  84864. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  84865. }
  84866. // Exposure
  84867. effect.setFloat("exposureLinear", this.exposure);
  84868. // Contrast
  84869. effect.setFloat("contrast", this.contrast);
  84870. // Color transform settings
  84871. if (this.colorGradingTexture) {
  84872. effect.setTexture("txColorTransform", this.colorGradingTexture);
  84873. var textureSize = this.colorGradingTexture.getSize().height;
  84874. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  84875. 0.5 / textureSize, // textureOffset
  84876. textureSize, // textureSize
  84877. this.colorGradingTexture.level // weight
  84878. );
  84879. }
  84880. };
  84881. /**
  84882. * Clones the current image processing instance.
  84883. * @return The cloned image processing
  84884. */
  84885. ImageProcessingConfiguration.prototype.clone = function () {
  84886. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84887. };
  84888. /**
  84889. * Serializes the current image processing instance to a json representation.
  84890. * @return a JSON representation
  84891. */
  84892. ImageProcessingConfiguration.prototype.serialize = function () {
  84893. return BABYLON.SerializationHelper.Serialize(this);
  84894. };
  84895. /**
  84896. * Parses the image processing from a json representation.
  84897. * @param source the JSON source to parse
  84898. * @return The parsed image processing
  84899. */
  84900. ImageProcessingConfiguration.Parse = function (source) {
  84901. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84902. };
  84903. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84904. /**
  84905. * Used to apply the vignette as a mix with the pixel color.
  84906. */
  84907. get: function () {
  84908. return this._VIGNETTEMODE_MULTIPLY;
  84909. },
  84910. enumerable: true,
  84911. configurable: true
  84912. });
  84913. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84914. /**
  84915. * Used to apply the vignette as a replacement of the pixel color.
  84916. */
  84917. get: function () {
  84918. return this._VIGNETTEMODE_OPAQUE;
  84919. },
  84920. enumerable: true,
  84921. configurable: true
  84922. });
  84923. /**
  84924. * Default tone mapping applied in BabylonJS.
  84925. */
  84926. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84927. /**
  84928. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84929. * to other engines rendering to increase portability.
  84930. */
  84931. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84932. // Static constants associated to the image processing.
  84933. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84934. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84935. __decorate([
  84936. BABYLON.serializeAsColorCurves()
  84937. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84938. __decorate([
  84939. BABYLON.serialize()
  84940. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84941. __decorate([
  84942. BABYLON.serializeAsTexture()
  84943. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84944. __decorate([
  84945. BABYLON.serialize()
  84946. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84947. __decorate([
  84948. BABYLON.serialize()
  84949. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84950. __decorate([
  84951. BABYLON.serialize()
  84952. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84953. __decorate([
  84954. BABYLON.serialize()
  84955. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84956. __decorate([
  84957. BABYLON.serialize()
  84958. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84959. __decorate([
  84960. BABYLON.serialize()
  84961. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84962. __decorate([
  84963. BABYLON.serialize()
  84964. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84965. __decorate([
  84966. BABYLON.serialize()
  84967. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84968. __decorate([
  84969. BABYLON.serialize()
  84970. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84971. __decorate([
  84972. BABYLON.serialize()
  84973. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  84974. __decorate([
  84975. BABYLON.serialize()
  84976. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  84977. __decorate([
  84978. BABYLON.serializeAsColor4()
  84979. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  84980. __decorate([
  84981. BABYLON.serialize()
  84982. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  84983. __decorate([
  84984. BABYLON.serialize()
  84985. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  84986. __decorate([
  84987. BABYLON.serialize()
  84988. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  84989. __decorate([
  84990. BABYLON.serialize()
  84991. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  84992. __decorate([
  84993. BABYLON.serialize()
  84994. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  84995. return ImageProcessingConfiguration;
  84996. }());
  84997. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  84998. })(BABYLON || (BABYLON = {}));
  84999. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  85000. var BABYLON;
  85001. (function (BABYLON) {
  85002. /**
  85003. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  85004. * It can help converting any input color in a desired output one. This can then be used to create effects
  85005. * from sepia, black and white to sixties or futuristic rendering...
  85006. *
  85007. * The only supported format is currently 3dl.
  85008. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  85009. */
  85010. var ColorGradingTexture = /** @class */ (function (_super) {
  85011. __extends(ColorGradingTexture, _super);
  85012. /**
  85013. * Instantiates a ColorGradingTexture from the following parameters.
  85014. *
  85015. * @param url The location of the color gradind data (currently only supporting 3dl)
  85016. * @param scene The scene the texture will be used in
  85017. */
  85018. function ColorGradingTexture(url, scene) {
  85019. var _this = _super.call(this, scene) || this;
  85020. if (!url) {
  85021. return _this;
  85022. }
  85023. _this._engine = scene.getEngine();
  85024. _this._textureMatrix = BABYLON.Matrix.Identity();
  85025. _this.name = url;
  85026. _this.url = url;
  85027. _this.hasAlpha = false;
  85028. _this.isCube = false;
  85029. _this.is3D = _this._engine.webGLVersion > 1;
  85030. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85031. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85032. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85033. _this.anisotropicFilteringLevel = 1;
  85034. _this._texture = _this._getFromCache(url, true);
  85035. if (!_this._texture) {
  85036. if (!scene.useDelayedTextureLoading) {
  85037. _this.loadTexture();
  85038. }
  85039. else {
  85040. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85041. }
  85042. }
  85043. return _this;
  85044. }
  85045. /**
  85046. * Returns the texture matrix used in most of the material.
  85047. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  85048. */
  85049. ColorGradingTexture.prototype.getTextureMatrix = function () {
  85050. return this._textureMatrix;
  85051. };
  85052. /**
  85053. * Occurs when the file being loaded is a .3dl LUT file.
  85054. */
  85055. ColorGradingTexture.prototype.load3dlTexture = function () {
  85056. var engine = this._engine;
  85057. var texture;
  85058. if (engine.webGLVersion === 1) {
  85059. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85060. }
  85061. else {
  85062. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85063. }
  85064. this._texture = texture;
  85065. var callback = function (text) {
  85066. if (typeof text !== "string") {
  85067. return;
  85068. }
  85069. var data = null;
  85070. var tempData = null;
  85071. var line;
  85072. var lines = text.split('\n');
  85073. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  85074. var maxColor = 0;
  85075. for (var i = 0; i < lines.length; i++) {
  85076. line = lines[i];
  85077. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  85078. continue;
  85079. if (line.indexOf('#') === 0)
  85080. continue;
  85081. var words = line.split(" ");
  85082. if (size === 0) {
  85083. // Number of space + one
  85084. size = words.length;
  85085. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  85086. tempData = new Float32Array(size * size * size * 4);
  85087. continue;
  85088. }
  85089. if (size != 0) {
  85090. var r = Math.max(parseInt(words[0]), 0);
  85091. var g = Math.max(parseInt(words[1]), 0);
  85092. var b = Math.max(parseInt(words[2]), 0);
  85093. maxColor = Math.max(r, maxColor);
  85094. maxColor = Math.max(g, maxColor);
  85095. maxColor = Math.max(b, maxColor);
  85096. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  85097. if (tempData) {
  85098. tempData[pixelStorageIndex + 0] = r;
  85099. tempData[pixelStorageIndex + 1] = g;
  85100. tempData[pixelStorageIndex + 2] = b;
  85101. }
  85102. pixelIndexSlice++;
  85103. if (pixelIndexSlice % size == 0) {
  85104. pixelIndexH++;
  85105. pixelIndexSlice = 0;
  85106. if (pixelIndexH % size == 0) {
  85107. pixelIndexW++;
  85108. pixelIndexH = 0;
  85109. }
  85110. }
  85111. }
  85112. }
  85113. if (tempData && data) {
  85114. for (var i = 0; i < tempData.length; i++) {
  85115. if (i > 0 && (i + 1) % 4 === 0) {
  85116. data[i] = 255;
  85117. }
  85118. else {
  85119. var value = tempData[i];
  85120. data[i] = (value / maxColor * 255);
  85121. }
  85122. }
  85123. }
  85124. if (texture.is3D) {
  85125. texture.updateSize(size, size, size);
  85126. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85127. }
  85128. else {
  85129. texture.updateSize(size * size, size);
  85130. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85131. }
  85132. };
  85133. var scene = this.getScene();
  85134. if (scene) {
  85135. scene._loadFile(this.url, callback);
  85136. }
  85137. else {
  85138. this._engine._loadFile(this.url, callback);
  85139. }
  85140. return this._texture;
  85141. };
  85142. /**
  85143. * Starts the loading process of the texture.
  85144. */
  85145. ColorGradingTexture.prototype.loadTexture = function () {
  85146. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  85147. this.load3dlTexture();
  85148. }
  85149. };
  85150. /**
  85151. * Clones the color gradind texture.
  85152. */
  85153. ColorGradingTexture.prototype.clone = function () {
  85154. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  85155. // Base texture
  85156. newTexture.level = this.level;
  85157. return newTexture;
  85158. };
  85159. /**
  85160. * Called during delayed load for textures.
  85161. */
  85162. ColorGradingTexture.prototype.delayLoad = function () {
  85163. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85164. return;
  85165. }
  85166. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85167. this._texture = this._getFromCache(this.url, true);
  85168. if (!this._texture) {
  85169. this.loadTexture();
  85170. }
  85171. };
  85172. /**
  85173. * Parses a color grading texture serialized by Babylon.
  85174. * @param parsedTexture The texture information being parsedTexture
  85175. * @param scene The scene to load the texture in
  85176. * @param rootUrl The root url of the data assets to load
  85177. * @return A color gradind texture
  85178. */
  85179. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85180. var texture = null;
  85181. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85182. texture = new ColorGradingTexture(parsedTexture.name, scene);
  85183. texture.name = parsedTexture.name;
  85184. texture.level = parsedTexture.level;
  85185. }
  85186. return texture;
  85187. };
  85188. /**
  85189. * Serializes the LUT texture to json format.
  85190. */
  85191. ColorGradingTexture.prototype.serialize = function () {
  85192. if (!this.name) {
  85193. return null;
  85194. }
  85195. var serializationObject = {};
  85196. serializationObject.name = this.name;
  85197. serializationObject.level = this.level;
  85198. serializationObject.customType = "BABYLON.ColorGradingTexture";
  85199. return serializationObject;
  85200. };
  85201. /**
  85202. * Empty line regex stored for GC.
  85203. */
  85204. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  85205. return ColorGradingTexture;
  85206. }(BABYLON.BaseTexture));
  85207. BABYLON.ColorGradingTexture = ColorGradingTexture;
  85208. })(BABYLON || (BABYLON = {}));
  85209. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  85210. var BABYLON;
  85211. (function (BABYLON) {
  85212. /**
  85213. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85214. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85215. * 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;
  85216. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85217. */
  85218. var ColorCurves = /** @class */ (function () {
  85219. function ColorCurves() {
  85220. this._dirty = true;
  85221. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  85222. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  85223. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85224. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  85225. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85226. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  85227. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  85228. this._globalHue = 30;
  85229. this._globalDensity = 0;
  85230. this._globalSaturation = 0;
  85231. this._globalExposure = 0;
  85232. this._highlightsHue = 30;
  85233. this._highlightsDensity = 0;
  85234. this._highlightsSaturation = 0;
  85235. this._highlightsExposure = 0;
  85236. this._midtonesHue = 30;
  85237. this._midtonesDensity = 0;
  85238. this._midtonesSaturation = 0;
  85239. this._midtonesExposure = 0;
  85240. this._shadowsHue = 30;
  85241. this._shadowsDensity = 0;
  85242. this._shadowsSaturation = 0;
  85243. this._shadowsExposure = 0;
  85244. }
  85245. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  85246. /**
  85247. * Gets the global Hue value.
  85248. * 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).
  85249. */
  85250. get: function () {
  85251. return this._globalHue;
  85252. },
  85253. /**
  85254. * Sets the global Hue value.
  85255. * 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).
  85256. */
  85257. set: function (value) {
  85258. this._globalHue = value;
  85259. this._dirty = true;
  85260. },
  85261. enumerable: true,
  85262. configurable: true
  85263. });
  85264. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  85265. /**
  85266. * Gets the global Density value.
  85267. * 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.
  85268. * Values less than zero provide a filter of opposite hue.
  85269. */
  85270. get: function () {
  85271. return this._globalDensity;
  85272. },
  85273. /**
  85274. * Sets the global Density value.
  85275. * 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.
  85276. * Values less than zero provide a filter of opposite hue.
  85277. */
  85278. set: function (value) {
  85279. this._globalDensity = value;
  85280. this._dirty = true;
  85281. },
  85282. enumerable: true,
  85283. configurable: true
  85284. });
  85285. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  85286. /**
  85287. * Gets the global Saturation value.
  85288. * 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.
  85289. */
  85290. get: function () {
  85291. return this._globalSaturation;
  85292. },
  85293. /**
  85294. * Sets the global Saturation value.
  85295. * 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.
  85296. */
  85297. set: function (value) {
  85298. this._globalSaturation = value;
  85299. this._dirty = true;
  85300. },
  85301. enumerable: true,
  85302. configurable: true
  85303. });
  85304. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  85305. /**
  85306. * Gets the global Exposure value.
  85307. * 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.
  85308. */
  85309. get: function () {
  85310. return this._globalExposure;
  85311. },
  85312. /**
  85313. * Sets the global Exposure value.
  85314. * 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.
  85315. */
  85316. set: function (value) {
  85317. this._globalExposure = value;
  85318. this._dirty = true;
  85319. },
  85320. enumerable: true,
  85321. configurable: true
  85322. });
  85323. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  85324. /**
  85325. * Gets the highlights Hue value.
  85326. * 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).
  85327. */
  85328. get: function () {
  85329. return this._highlightsHue;
  85330. },
  85331. /**
  85332. * Sets the highlights Hue value.
  85333. * 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).
  85334. */
  85335. set: function (value) {
  85336. this._highlightsHue = value;
  85337. this._dirty = true;
  85338. },
  85339. enumerable: true,
  85340. configurable: true
  85341. });
  85342. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  85343. /**
  85344. * Gets the highlights Density value.
  85345. * 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.
  85346. * Values less than zero provide a filter of opposite hue.
  85347. */
  85348. get: function () {
  85349. return this._highlightsDensity;
  85350. },
  85351. /**
  85352. * Sets the highlights Density value.
  85353. * 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.
  85354. * Values less than zero provide a filter of opposite hue.
  85355. */
  85356. set: function (value) {
  85357. this._highlightsDensity = value;
  85358. this._dirty = true;
  85359. },
  85360. enumerable: true,
  85361. configurable: true
  85362. });
  85363. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  85364. /**
  85365. * Gets the highlights Saturation value.
  85366. * 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.
  85367. */
  85368. get: function () {
  85369. return this._highlightsSaturation;
  85370. },
  85371. /**
  85372. * Sets the highlights Saturation value.
  85373. * 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.
  85374. */
  85375. set: function (value) {
  85376. this._highlightsSaturation = value;
  85377. this._dirty = true;
  85378. },
  85379. enumerable: true,
  85380. configurable: true
  85381. });
  85382. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  85383. /**
  85384. * Gets the highlights Exposure value.
  85385. * 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.
  85386. */
  85387. get: function () {
  85388. return this._highlightsExposure;
  85389. },
  85390. /**
  85391. * Sets the highlights Exposure value.
  85392. * 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.
  85393. */
  85394. set: function (value) {
  85395. this._highlightsExposure = value;
  85396. this._dirty = true;
  85397. },
  85398. enumerable: true,
  85399. configurable: true
  85400. });
  85401. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  85402. /**
  85403. * Gets the midtones Hue value.
  85404. * 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).
  85405. */
  85406. get: function () {
  85407. return this._midtonesHue;
  85408. },
  85409. /**
  85410. * Sets the midtones Hue value.
  85411. * 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).
  85412. */
  85413. set: function (value) {
  85414. this._midtonesHue = value;
  85415. this._dirty = true;
  85416. },
  85417. enumerable: true,
  85418. configurable: true
  85419. });
  85420. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  85421. /**
  85422. * Gets the midtones Density value.
  85423. * 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.
  85424. * Values less than zero provide a filter of opposite hue.
  85425. */
  85426. get: function () {
  85427. return this._midtonesDensity;
  85428. },
  85429. /**
  85430. * Sets the midtones Density value.
  85431. * 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.
  85432. * Values less than zero provide a filter of opposite hue.
  85433. */
  85434. set: function (value) {
  85435. this._midtonesDensity = value;
  85436. this._dirty = true;
  85437. },
  85438. enumerable: true,
  85439. configurable: true
  85440. });
  85441. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  85442. /**
  85443. * Gets the midtones Saturation value.
  85444. * 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.
  85445. */
  85446. get: function () {
  85447. return this._midtonesSaturation;
  85448. },
  85449. /**
  85450. * Sets the midtones Saturation value.
  85451. * 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.
  85452. */
  85453. set: function (value) {
  85454. this._midtonesSaturation = value;
  85455. this._dirty = true;
  85456. },
  85457. enumerable: true,
  85458. configurable: true
  85459. });
  85460. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  85461. /**
  85462. * Gets the midtones Exposure value.
  85463. * 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.
  85464. */
  85465. get: function () {
  85466. return this._midtonesExposure;
  85467. },
  85468. /**
  85469. * Sets the midtones Exposure value.
  85470. * 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.
  85471. */
  85472. set: function (value) {
  85473. this._midtonesExposure = value;
  85474. this._dirty = true;
  85475. },
  85476. enumerable: true,
  85477. configurable: true
  85478. });
  85479. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  85480. /**
  85481. * Gets the shadows Hue value.
  85482. * 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).
  85483. */
  85484. get: function () {
  85485. return this._shadowsHue;
  85486. },
  85487. /**
  85488. * Sets the shadows Hue value.
  85489. * 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).
  85490. */
  85491. set: function (value) {
  85492. this._shadowsHue = value;
  85493. this._dirty = true;
  85494. },
  85495. enumerable: true,
  85496. configurable: true
  85497. });
  85498. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  85499. /**
  85500. * Gets the shadows Density value.
  85501. * 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.
  85502. * Values less than zero provide a filter of opposite hue.
  85503. */
  85504. get: function () {
  85505. return this._shadowsDensity;
  85506. },
  85507. /**
  85508. * Sets the shadows Density value.
  85509. * 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.
  85510. * Values less than zero provide a filter of opposite hue.
  85511. */
  85512. set: function (value) {
  85513. this._shadowsDensity = value;
  85514. this._dirty = true;
  85515. },
  85516. enumerable: true,
  85517. configurable: true
  85518. });
  85519. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85520. /**
  85521. * Gets the shadows Saturation value.
  85522. * 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.
  85523. */
  85524. get: function () {
  85525. return this._shadowsSaturation;
  85526. },
  85527. /**
  85528. * Sets the shadows Saturation value.
  85529. * 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.
  85530. */
  85531. set: function (value) {
  85532. this._shadowsSaturation = value;
  85533. this._dirty = true;
  85534. },
  85535. enumerable: true,
  85536. configurable: true
  85537. });
  85538. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85539. /**
  85540. * Gets the shadows Exposure value.
  85541. * 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.
  85542. */
  85543. get: function () {
  85544. return this._shadowsExposure;
  85545. },
  85546. /**
  85547. * Sets the shadows Exposure value.
  85548. * 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.
  85549. */
  85550. set: function (value) {
  85551. this._shadowsExposure = value;
  85552. this._dirty = true;
  85553. },
  85554. enumerable: true,
  85555. configurable: true
  85556. });
  85557. ColorCurves.prototype.getClassName = function () {
  85558. return "ColorCurves";
  85559. };
  85560. /**
  85561. * Binds the color curves to the shader.
  85562. * @param colorCurves The color curve to bind
  85563. * @param effect The effect to bind to
  85564. */
  85565. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85566. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85567. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85568. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85569. if (colorCurves._dirty) {
  85570. colorCurves._dirty = false;
  85571. // Fill in global info.
  85572. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85573. // Compute highlights info.
  85574. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85575. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85576. // Compute midtones info.
  85577. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85578. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85579. // Compute shadows info.
  85580. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85581. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85582. // Compute deltas (neutral is midtones).
  85583. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85584. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85585. }
  85586. if (effect) {
  85587. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85588. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85589. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85590. }
  85591. };
  85592. /**
  85593. * Prepare the list of uniforms associated with the ColorCurves effects.
  85594. * @param uniformsList The list of uniforms used in the effect
  85595. */
  85596. ColorCurves.PrepareUniforms = function (uniformsList) {
  85597. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85598. };
  85599. /**
  85600. * Returns color grading data based on a hue, density, saturation and exposure value.
  85601. * @param filterHue The hue of the color filter.
  85602. * @param filterDensity The density of the color filter.
  85603. * @param saturation The saturation.
  85604. * @param exposure The exposure.
  85605. * @param result The result data container.
  85606. */
  85607. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85608. if (hue == null) {
  85609. return;
  85610. }
  85611. hue = ColorCurves.clamp(hue, 0, 360);
  85612. density = ColorCurves.clamp(density, -100, 100);
  85613. saturation = ColorCurves.clamp(saturation, -100, 100);
  85614. exposure = ColorCurves.clamp(exposure, -100, 100);
  85615. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85616. // so that the maximum filter density is only 50% control. This provides fine control
  85617. // for small values and reasonable range.
  85618. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85619. density *= 0.5;
  85620. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85621. if (density < 0) {
  85622. density *= -1;
  85623. hue = (hue + 180) % 360;
  85624. }
  85625. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85626. result.scaleToRef(2, result);
  85627. result.a = 1 + 0.01 * saturation;
  85628. };
  85629. /**
  85630. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  85631. * @param value The input slider value in range [-100,100].
  85632. * @returns Adjusted value.
  85633. */
  85634. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  85635. value /= 100;
  85636. var x = Math.abs(value);
  85637. x = Math.pow(x, 2);
  85638. if (value < 0) {
  85639. x *= -1;
  85640. }
  85641. x *= 100;
  85642. return x;
  85643. };
  85644. /**
  85645. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  85646. * @param hue The hue (H) input.
  85647. * @param saturation The saturation (S) input.
  85648. * @param brightness The brightness (B) input.
  85649. * @result An RGBA color represented as Vector4.
  85650. */
  85651. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  85652. var h = ColorCurves.clamp(hue, 0, 360);
  85653. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  85654. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  85655. if (s === 0) {
  85656. result.r = v;
  85657. result.g = v;
  85658. result.b = v;
  85659. }
  85660. else {
  85661. // sector 0 to 5
  85662. h /= 60;
  85663. var i = Math.floor(h);
  85664. // fractional part of h
  85665. var f = h - i;
  85666. var p = v * (1 - s);
  85667. var q = v * (1 - s * f);
  85668. var t = v * (1 - s * (1 - f));
  85669. switch (i) {
  85670. case 0:
  85671. result.r = v;
  85672. result.g = t;
  85673. result.b = p;
  85674. break;
  85675. case 1:
  85676. result.r = q;
  85677. result.g = v;
  85678. result.b = p;
  85679. break;
  85680. case 2:
  85681. result.r = p;
  85682. result.g = v;
  85683. result.b = t;
  85684. break;
  85685. case 3:
  85686. result.r = p;
  85687. result.g = q;
  85688. result.b = v;
  85689. break;
  85690. case 4:
  85691. result.r = t;
  85692. result.g = p;
  85693. result.b = v;
  85694. break;
  85695. default: // case 5:
  85696. result.r = v;
  85697. result.g = p;
  85698. result.b = q;
  85699. break;
  85700. }
  85701. }
  85702. result.a = 1;
  85703. };
  85704. /**
  85705. * Returns a value clamped between min and max
  85706. * @param value The value to clamp
  85707. * @param min The minimum of value
  85708. * @param max The maximum of value
  85709. * @returns The clamped value.
  85710. */
  85711. ColorCurves.clamp = function (value, min, max) {
  85712. return Math.min(Math.max(value, min), max);
  85713. };
  85714. /**
  85715. * Clones the current color curve instance.
  85716. * @return The cloned curves
  85717. */
  85718. ColorCurves.prototype.clone = function () {
  85719. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  85720. };
  85721. /**
  85722. * Serializes the current color curve instance to a json representation.
  85723. * @return a JSON representation
  85724. */
  85725. ColorCurves.prototype.serialize = function () {
  85726. return BABYLON.SerializationHelper.Serialize(this);
  85727. };
  85728. /**
  85729. * Parses the color curve from a json representation.
  85730. * @param source the JSON source to parse
  85731. * @return The parsed curves
  85732. */
  85733. ColorCurves.Parse = function (source) {
  85734. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  85735. };
  85736. __decorate([
  85737. BABYLON.serialize()
  85738. ], ColorCurves.prototype, "_globalHue", void 0);
  85739. __decorate([
  85740. BABYLON.serialize()
  85741. ], ColorCurves.prototype, "_globalDensity", void 0);
  85742. __decorate([
  85743. BABYLON.serialize()
  85744. ], ColorCurves.prototype, "_globalSaturation", void 0);
  85745. __decorate([
  85746. BABYLON.serialize()
  85747. ], ColorCurves.prototype, "_globalExposure", void 0);
  85748. __decorate([
  85749. BABYLON.serialize()
  85750. ], ColorCurves.prototype, "_highlightsHue", void 0);
  85751. __decorate([
  85752. BABYLON.serialize()
  85753. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  85754. __decorate([
  85755. BABYLON.serialize()
  85756. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  85757. __decorate([
  85758. BABYLON.serialize()
  85759. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  85760. __decorate([
  85761. BABYLON.serialize()
  85762. ], ColorCurves.prototype, "_midtonesHue", void 0);
  85763. __decorate([
  85764. BABYLON.serialize()
  85765. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  85766. __decorate([
  85767. BABYLON.serialize()
  85768. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  85769. __decorate([
  85770. BABYLON.serialize()
  85771. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  85772. return ColorCurves;
  85773. }());
  85774. BABYLON.ColorCurves = ColorCurves;
  85775. })(BABYLON || (BABYLON = {}));
  85776. //# sourceMappingURL=babylon.colorCurves.js.map
  85777. var BABYLON;
  85778. (function (BABYLON) {
  85779. var RefractionPostProcess = /** @class */ (function (_super) {
  85780. __extends(RefractionPostProcess, _super);
  85781. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  85782. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  85783. _this.color = color;
  85784. _this.depth = depth;
  85785. _this.colorLevel = colorLevel;
  85786. _this._ownRefractionTexture = true;
  85787. _this.onActivateObservable.add(function (cam) {
  85788. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  85789. });
  85790. _this.onApplyObservable.add(function (effect) {
  85791. effect.setColor3("baseColor", _this.color);
  85792. effect.setFloat("depth", _this.depth);
  85793. effect.setFloat("colorLevel", _this.colorLevel);
  85794. effect.setTexture("refractionSampler", _this._refTexture);
  85795. });
  85796. return _this;
  85797. }
  85798. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  85799. /**
  85800. * Gets or sets the refraction texture
  85801. * Please note that you are responsible for disposing the texture if you set it manually
  85802. */
  85803. get: function () {
  85804. return this._refTexture;
  85805. },
  85806. set: function (value) {
  85807. if (this._refTexture && this._ownRefractionTexture) {
  85808. this._refTexture.dispose();
  85809. }
  85810. this._refTexture = value;
  85811. this._ownRefractionTexture = false;
  85812. },
  85813. enumerable: true,
  85814. configurable: true
  85815. });
  85816. // Methods
  85817. RefractionPostProcess.prototype.dispose = function (camera) {
  85818. if (this._refTexture && this._ownRefractionTexture) {
  85819. this._refTexture.dispose();
  85820. this._refTexture = null;
  85821. }
  85822. _super.prototype.dispose.call(this, camera);
  85823. };
  85824. return RefractionPostProcess;
  85825. }(BABYLON.PostProcess));
  85826. BABYLON.RefractionPostProcess = RefractionPostProcess;
  85827. })(BABYLON || (BABYLON = {}));
  85828. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  85829. var BABYLON;
  85830. (function (BABYLON) {
  85831. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  85832. __extends(BlackAndWhitePostProcess, _super);
  85833. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  85834. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  85835. _this.degree = 1;
  85836. _this.onApplyObservable.add(function (effect) {
  85837. effect.setFloat("degree", _this.degree);
  85838. });
  85839. return _this;
  85840. }
  85841. return BlackAndWhitePostProcess;
  85842. }(BABYLON.PostProcess));
  85843. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  85844. })(BABYLON || (BABYLON = {}));
  85845. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  85846. var BABYLON;
  85847. (function (BABYLON) {
  85848. /**
  85849. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  85850. * input texture to perform effects such as edge detection or sharpening
  85851. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85852. */
  85853. var ConvolutionPostProcess = /** @class */ (function (_super) {
  85854. __extends(ConvolutionPostProcess, _super);
  85855. /**
  85856. * Creates a new instance ConvolutionPostProcess
  85857. * @param name The name of the effect.
  85858. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  85859. * @param options The required width/height ratio to downsize to before computing the render pass.
  85860. * @param camera The camera to apply the render pass to.
  85861. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85862. * @param engine The engine which the post process will be applied. (default: current engine)
  85863. * @param reusable If the post process can be reused on the same frame. (default: false)
  85864. * @param textureType Type of textures used when performing the post process. (default: 0)
  85865. */
  85866. function ConvolutionPostProcess(name,
  85867. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  85868. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  85869. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85870. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85871. _this.kernel = kernel;
  85872. _this.onApply = function (effect) {
  85873. effect.setFloat2("screenSize", _this.width, _this.height);
  85874. effect.setArray("kernel", _this.kernel);
  85875. };
  85876. return _this;
  85877. }
  85878. // Statics
  85879. /**
  85880. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85881. */
  85882. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85883. /**
  85884. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85885. */
  85886. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85887. /**
  85888. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85889. */
  85890. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85891. /**
  85892. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85893. */
  85894. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85895. /**
  85896. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85897. */
  85898. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85899. /**
  85900. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85901. */
  85902. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85903. return ConvolutionPostProcess;
  85904. }(BABYLON.PostProcess));
  85905. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85906. })(BABYLON || (BABYLON = {}));
  85907. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85908. var BABYLON;
  85909. (function (BABYLON) {
  85910. var FilterPostProcess = /** @class */ (function (_super) {
  85911. __extends(FilterPostProcess, _super);
  85912. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85913. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85914. _this.kernelMatrix = kernelMatrix;
  85915. _this.onApply = function (effect) {
  85916. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85917. };
  85918. return _this;
  85919. }
  85920. return FilterPostProcess;
  85921. }(BABYLON.PostProcess));
  85922. BABYLON.FilterPostProcess = FilterPostProcess;
  85923. })(BABYLON || (BABYLON = {}));
  85924. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85925. var BABYLON;
  85926. (function (BABYLON) {
  85927. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85928. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85929. __extends(VolumetricLightScatteringPostProcess, _super);
  85930. /**
  85931. * @constructor
  85932. * @param {string} name - The post-process name
  85933. * @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)
  85934. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85935. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85936. * @param {number} samples - The post-process quality, default 100
  85937. * @param {number} samplingMode - The post-process filtering mode
  85938. * @param {BABYLON.Engine} engine - The babylon engine
  85939. * @param {boolean} reusable - If the post-process is reusable
  85940. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85941. */
  85942. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85943. if (samples === void 0) { samples = 100; }
  85944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85945. 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;
  85946. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85947. /**
  85948. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85949. */
  85950. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85951. /**
  85952. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85953. */
  85954. _this.useCustomMeshPosition = false;
  85955. /**
  85956. * If the post-process should inverse the light scattering direction
  85957. */
  85958. _this.invert = true;
  85959. /**
  85960. * Array containing the excluded meshes not rendered in the internal pass
  85961. */
  85962. _this.excludedMeshes = new Array();
  85963. /**
  85964. * Controls the overall intensity of the post-process
  85965. */
  85966. _this.exposure = 0.3;
  85967. /**
  85968. * Dissipates each sample's contribution in range [0, 1]
  85969. */
  85970. _this.decay = 0.96815;
  85971. /**
  85972. * Controls the overall intensity of each sample
  85973. */
  85974. _this.weight = 0.58767;
  85975. /**
  85976. * Controls the density of each sample
  85977. */
  85978. _this.density = 0.926;
  85979. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  85980. engine = scene.getEngine();
  85981. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  85982. // Configure mesh
  85983. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  85984. // Configure
  85985. _this._createPass(scene, ratio.passRatio || ratio);
  85986. _this.onActivate = function (camera) {
  85987. if (!_this.isSupported) {
  85988. _this.dispose(camera);
  85989. }
  85990. _this.onActivate = null;
  85991. };
  85992. _this.onApplyObservable.add(function (effect) {
  85993. _this._updateMeshScreenCoordinates(scene);
  85994. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  85995. effect.setFloat("exposure", _this.exposure);
  85996. effect.setFloat("decay", _this.decay);
  85997. effect.setFloat("weight", _this.weight);
  85998. effect.setFloat("density", _this.density);
  85999. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  86000. });
  86001. return _this;
  86002. }
  86003. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  86004. get: function () {
  86005. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86006. return false;
  86007. },
  86008. set: function (useDiffuseColor) {
  86009. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86010. },
  86011. enumerable: true,
  86012. configurable: true
  86013. });
  86014. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  86015. return "VolumetricLightScatteringPostProcess";
  86016. };
  86017. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  86018. var mesh = subMesh.getMesh();
  86019. // Render this.mesh as default
  86020. if (mesh === this.mesh && mesh.material) {
  86021. return mesh.material.isReady(mesh);
  86022. }
  86023. var defines = [];
  86024. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86025. var material = subMesh.getMaterial();
  86026. // Alpha test
  86027. if (material) {
  86028. if (material.needAlphaTesting()) {
  86029. defines.push("#define ALPHATEST");
  86030. }
  86031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86032. attribs.push(BABYLON.VertexBuffer.UVKind);
  86033. defines.push("#define UV1");
  86034. }
  86035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86036. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86037. defines.push("#define UV2");
  86038. }
  86039. }
  86040. // Bones
  86041. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86044. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86045. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86046. }
  86047. else {
  86048. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86049. }
  86050. // Instances
  86051. if (useInstances) {
  86052. defines.push("#define INSTANCES");
  86053. attribs.push("world0");
  86054. attribs.push("world1");
  86055. attribs.push("world2");
  86056. attribs.push("world3");
  86057. }
  86058. // Get correct effect
  86059. var join = defines.join("\n");
  86060. if (this._cachedDefines !== join) {
  86061. this._cachedDefines = join;
  86062. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  86063. }
  86064. return this._volumetricLightScatteringPass.isReady();
  86065. };
  86066. /**
  86067. * Sets the new light position for light scattering effect
  86068. * @param {BABYLON.Vector3} The new custom light position
  86069. */
  86070. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  86071. this.customMeshPosition = position;
  86072. };
  86073. /**
  86074. * Returns the light position for light scattering effect
  86075. * @return {BABYLON.Vector3} The custom light position
  86076. */
  86077. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  86078. return this.customMeshPosition;
  86079. };
  86080. /**
  86081. * Disposes the internal assets and detaches the post-process from the camera
  86082. */
  86083. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  86084. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  86085. if (rttIndex !== -1) {
  86086. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  86087. }
  86088. this._volumetricLightScatteringRTT.dispose();
  86089. _super.prototype.dispose.call(this, camera);
  86090. };
  86091. /**
  86092. * Returns the render target texture used by the post-process
  86093. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  86094. */
  86095. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  86096. return this._volumetricLightScatteringRTT;
  86097. };
  86098. // Private methods
  86099. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  86100. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  86101. return true;
  86102. }
  86103. return false;
  86104. };
  86105. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  86106. var _this = this;
  86107. var engine = scene.getEngine();
  86108. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86109. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86110. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86111. this._volumetricLightScatteringRTT.renderList = null;
  86112. this._volumetricLightScatteringRTT.renderParticles = false;
  86113. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  86114. var camera = this.getCamera();
  86115. if (camera) {
  86116. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86117. }
  86118. else {
  86119. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86120. }
  86121. // Custom render function for submeshes
  86122. var renderSubMesh = function (subMesh) {
  86123. var mesh = subMesh.getRenderingMesh();
  86124. if (_this._meshExcluded(mesh)) {
  86125. return;
  86126. }
  86127. var material = subMesh.getMaterial();
  86128. if (!material) {
  86129. return;
  86130. }
  86131. var scene = mesh.getScene();
  86132. var engine = scene.getEngine();
  86133. // Culling
  86134. engine.setState(material.backFaceCulling);
  86135. // Managing instances
  86136. var batch = mesh._getInstancesRenderList(subMesh._id);
  86137. if (batch.mustReturn) {
  86138. return;
  86139. }
  86140. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86141. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  86142. var effect = _this._volumetricLightScatteringPass;
  86143. if (mesh === _this.mesh) {
  86144. if (subMesh.effect) {
  86145. effect = subMesh.effect;
  86146. }
  86147. else {
  86148. effect = material.getEffect();
  86149. }
  86150. }
  86151. engine.enableEffect(effect);
  86152. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  86153. if (mesh === _this.mesh) {
  86154. material.bind(mesh.getWorldMatrix(), mesh);
  86155. }
  86156. else {
  86157. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  86158. // Alpha test
  86159. if (material && material.needAlphaTesting()) {
  86160. var alphaTexture = material.getAlphaTestTexture();
  86161. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  86162. if (alphaTexture) {
  86163. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86164. }
  86165. }
  86166. // Bones
  86167. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86168. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86169. }
  86170. }
  86171. // Draw
  86172. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  86173. }
  86174. };
  86175. // Render target texture callbacks
  86176. var savedSceneClearColor;
  86177. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  86178. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  86179. savedSceneClearColor = scene.clearColor;
  86180. scene.clearColor = sceneClearColor;
  86181. });
  86182. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  86183. scene.clearColor = savedSceneClearColor;
  86184. });
  86185. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86186. var engine = scene.getEngine();
  86187. var index;
  86188. if (depthOnlySubMeshes.length) {
  86189. engine.setColorWrite(false);
  86190. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86191. renderSubMesh(depthOnlySubMeshes.data[index]);
  86192. }
  86193. engine.setColorWrite(true);
  86194. }
  86195. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86196. renderSubMesh(opaqueSubMeshes.data[index]);
  86197. }
  86198. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86199. renderSubMesh(alphaTestSubMeshes.data[index]);
  86200. }
  86201. if (transparentSubMeshes.length) {
  86202. // Sort sub meshes
  86203. for (index = 0; index < transparentSubMeshes.length; index++) {
  86204. var submesh = transparentSubMeshes.data[index];
  86205. var boundingInfo = submesh.getBoundingInfo();
  86206. if (boundingInfo && scene.activeCamera) {
  86207. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  86208. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  86209. }
  86210. }
  86211. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  86212. sortedArray.sort(function (a, b) {
  86213. // Alpha index first
  86214. if (a._alphaIndex > b._alphaIndex) {
  86215. return 1;
  86216. }
  86217. if (a._alphaIndex < b._alphaIndex) {
  86218. return -1;
  86219. }
  86220. // Then distance to camera
  86221. if (a._distanceToCamera < b._distanceToCamera) {
  86222. return 1;
  86223. }
  86224. if (a._distanceToCamera > b._distanceToCamera) {
  86225. return -1;
  86226. }
  86227. return 0;
  86228. });
  86229. // Render sub meshes
  86230. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  86231. for (index = 0; index < sortedArray.length; index++) {
  86232. renderSubMesh(sortedArray[index]);
  86233. }
  86234. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86235. }
  86236. };
  86237. };
  86238. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  86239. var transform = scene.getTransformMatrix();
  86240. var meshPosition;
  86241. if (this.useCustomMeshPosition) {
  86242. meshPosition = this.customMeshPosition;
  86243. }
  86244. else if (this.attachedNode) {
  86245. meshPosition = this.attachedNode.position;
  86246. }
  86247. else {
  86248. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  86249. }
  86250. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  86251. this._screenCoordinates.x = pos.x / this._viewPort.width;
  86252. this._screenCoordinates.y = pos.y / this._viewPort.height;
  86253. if (this.invert)
  86254. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  86255. };
  86256. // Static methods
  86257. /**
  86258. * Creates a default mesh for the Volumeric Light Scattering post-process
  86259. * @param {string} The mesh name
  86260. * @param {BABYLON.Scene} The scene where to create the mesh
  86261. * @return {BABYLON.Mesh} the default mesh
  86262. */
  86263. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  86264. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  86265. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  86266. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  86267. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  86268. mesh.material = material;
  86269. return mesh;
  86270. };
  86271. __decorate([
  86272. BABYLON.serializeAsVector3()
  86273. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  86274. __decorate([
  86275. BABYLON.serialize()
  86276. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  86277. __decorate([
  86278. BABYLON.serialize()
  86279. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  86280. __decorate([
  86281. BABYLON.serializeAsMeshReference()
  86282. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  86283. __decorate([
  86284. BABYLON.serialize()
  86285. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  86286. __decorate([
  86287. BABYLON.serialize()
  86288. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  86289. __decorate([
  86290. BABYLON.serialize()
  86291. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  86292. __decorate([
  86293. BABYLON.serialize()
  86294. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  86295. __decorate([
  86296. BABYLON.serialize()
  86297. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  86298. return VolumetricLightScatteringPostProcess;
  86299. }(BABYLON.PostProcess));
  86300. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  86301. })(BABYLON || (BABYLON = {}));
  86302. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  86303. //
  86304. // This post-process allows the modification of rendered colors by using
  86305. // a 'look-up table' (LUT). This effect is also called Color Grading.
  86306. //
  86307. // The object needs to be provided an url to a texture containing the color
  86308. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  86309. // Use an image editing software to tweak the LUT to match your needs.
  86310. //
  86311. // For an example of a color LUT, see here:
  86312. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  86313. // For explanations on color grading, see here:
  86314. // http://udn.epicgames.com/Three/ColorGrading.html
  86315. //
  86316. var BABYLON;
  86317. (function (BABYLON) {
  86318. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  86319. __extends(ColorCorrectionPostProcess, _super);
  86320. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  86321. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  86322. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86323. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  86324. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86325. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86326. _this.onApply = function (effect) {
  86327. effect.setTexture("colorTable", _this._colorTableTexture);
  86328. };
  86329. return _this;
  86330. }
  86331. return ColorCorrectionPostProcess;
  86332. }(BABYLON.PostProcess));
  86333. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  86334. })(BABYLON || (BABYLON = {}));
  86335. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  86336. var BABYLON;
  86337. (function (BABYLON) {
  86338. /** Defines operator used for tonemapping */
  86339. var TonemappingOperator;
  86340. (function (TonemappingOperator) {
  86341. /** Hable */
  86342. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  86343. /** Reinhard */
  86344. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  86345. /** HejiDawson */
  86346. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  86347. /** Photographic */
  86348. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  86349. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  86350. ;
  86351. /**
  86352. * Defines a post process to apply tone mapping
  86353. */
  86354. var TonemapPostProcess = /** @class */ (function (_super) {
  86355. __extends(TonemapPostProcess, _super);
  86356. /**
  86357. * Creates a new TonemapPostProcess
  86358. * @param name defines the name of the postprocess
  86359. * @param _operator defines the operator to use
  86360. * @param exposureAdjustment defines the required exposure adjustement
  86361. * @param camera defines the camera to use (can be null)
  86362. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  86363. * @param engine defines the hosting engine (can be ignore if camera is set)
  86364. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  86365. */
  86366. function TonemapPostProcess(name, _operator,
  86367. /** Defines the required exposure adjustement */
  86368. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  86369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86370. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86371. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  86372. _this._operator = _operator;
  86373. _this.exposureAdjustment = exposureAdjustment;
  86374. var defines = "#define ";
  86375. if (_this._operator === TonemappingOperator.Hable)
  86376. defines += "HABLE_TONEMAPPING";
  86377. else if (_this._operator === TonemappingOperator.Reinhard)
  86378. defines += "REINHARD_TONEMAPPING";
  86379. else if (_this._operator === TonemappingOperator.HejiDawson)
  86380. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  86381. else if (_this._operator === TonemappingOperator.Photographic)
  86382. defines += "PHOTOGRAPHIC_TONEMAPPING";
  86383. //sadly a second call to create the effect.
  86384. _this.updateEffect(defines);
  86385. _this.onApply = function (effect) {
  86386. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  86387. };
  86388. return _this;
  86389. }
  86390. return TonemapPostProcess;
  86391. }(BABYLON.PostProcess));
  86392. BABYLON.TonemapPostProcess = TonemapPostProcess;
  86393. })(BABYLON || (BABYLON = {}));
  86394. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  86395. var BABYLON;
  86396. (function (BABYLON) {
  86397. var DisplayPassPostProcess = /** @class */ (function (_super) {
  86398. __extends(DisplayPassPostProcess, _super);
  86399. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  86400. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  86401. }
  86402. return DisplayPassPostProcess;
  86403. }(BABYLON.PostProcess));
  86404. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  86405. })(BABYLON || (BABYLON = {}));
  86406. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  86407. var BABYLON;
  86408. (function (BABYLON) {
  86409. var HighlightsPostProcess = /** @class */ (function (_super) {
  86410. __extends(HighlightsPostProcess, _super);
  86411. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86412. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86413. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86414. }
  86415. return HighlightsPostProcess;
  86416. }(BABYLON.PostProcess));
  86417. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  86418. })(BABYLON || (BABYLON = {}));
  86419. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  86420. var BABYLON;
  86421. (function (BABYLON) {
  86422. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  86423. __extends(ImageProcessingPostProcess, _super);
  86424. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  86425. if (camera === void 0) { camera = null; }
  86426. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86427. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  86428. _this._fromLinearSpace = true;
  86429. /**
  86430. * Defines cache preventing GC.
  86431. */
  86432. _this._defines = {
  86433. IMAGEPROCESSING: false,
  86434. VIGNETTE: false,
  86435. VIGNETTEBLENDMODEMULTIPLY: false,
  86436. VIGNETTEBLENDMODEOPAQUE: false,
  86437. TONEMAPPING: false,
  86438. TONEMAPPING_ACES: false,
  86439. CONTRAST: false,
  86440. COLORCURVES: false,
  86441. COLORGRADING: false,
  86442. COLORGRADING3D: false,
  86443. FROMLINEARSPACE: false,
  86444. SAMPLER3DGREENDEPTH: false,
  86445. SAMPLER3DBGRMAP: false,
  86446. IMAGEPROCESSINGPOSTPROCESS: false,
  86447. EXPOSURE: false,
  86448. };
  86449. // Setup the configuration as forced by the constructor. This would then not force the
  86450. // scene materials output in linear space and let untouched the default forward pass.
  86451. if (imageProcessingConfiguration) {
  86452. imageProcessingConfiguration.applyByPostProcess = true;
  86453. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  86454. // This will cause the shader to be compiled
  86455. _this.fromLinearSpace = false;
  86456. }
  86457. // Setup the default processing configuration to the scene.
  86458. else {
  86459. _this._attachImageProcessingConfiguration(null, true);
  86460. _this.imageProcessingConfiguration.applyByPostProcess = true;
  86461. }
  86462. _this.onApply = function (effect) {
  86463. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  86464. };
  86465. return _this;
  86466. }
  86467. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  86468. /**
  86469. * Gets the image processing configuration used either in this material.
  86470. */
  86471. get: function () {
  86472. return this._imageProcessingConfiguration;
  86473. },
  86474. /**
  86475. * Sets the Default image processing configuration used either in the this material.
  86476. *
  86477. * If sets to null, the scene one is in use.
  86478. */
  86479. set: function (value) {
  86480. this._attachImageProcessingConfiguration(value);
  86481. },
  86482. enumerable: true,
  86483. configurable: true
  86484. });
  86485. /**
  86486. * Attaches a new image processing configuration to the PBR Material.
  86487. * @param configuration
  86488. */
  86489. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  86490. var _this = this;
  86491. if (doNotBuild === void 0) { doNotBuild = false; }
  86492. if (configuration === this._imageProcessingConfiguration) {
  86493. return;
  86494. }
  86495. // Detaches observer.
  86496. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86497. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86498. }
  86499. // Pick the scene configuration if needed.
  86500. if (!configuration) {
  86501. var scene = null;
  86502. var engine = this.getEngine();
  86503. var camera = this.getCamera();
  86504. if (camera) {
  86505. scene = camera.getScene();
  86506. }
  86507. else if (engine && engine.scenes) {
  86508. var scenes = engine.scenes;
  86509. scene = scenes[scenes.length - 1];
  86510. }
  86511. else {
  86512. scene = BABYLON.Engine.LastCreatedScene;
  86513. }
  86514. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86515. }
  86516. else {
  86517. this._imageProcessingConfiguration = configuration;
  86518. }
  86519. // Attaches observer.
  86520. if (this._imageProcessingConfiguration) {
  86521. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86522. _this._updateParameters();
  86523. });
  86524. }
  86525. // Ensure the effect will be rebuilt.
  86526. if (!doNotBuild) {
  86527. this._updateParameters();
  86528. }
  86529. };
  86530. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86531. /**
  86532. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86533. */
  86534. get: function () {
  86535. return this.imageProcessingConfiguration.colorCurves;
  86536. },
  86537. /**
  86538. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86539. */
  86540. set: function (value) {
  86541. this.imageProcessingConfiguration.colorCurves = value;
  86542. },
  86543. enumerable: true,
  86544. configurable: true
  86545. });
  86546. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86547. /**
  86548. * Gets wether the color curves effect is enabled.
  86549. */
  86550. get: function () {
  86551. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86552. },
  86553. /**
  86554. * Sets wether the color curves effect is enabled.
  86555. */
  86556. set: function (value) {
  86557. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86558. },
  86559. enumerable: true,
  86560. configurable: true
  86561. });
  86562. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86563. /**
  86564. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86565. */
  86566. get: function () {
  86567. return this.imageProcessingConfiguration.colorGradingTexture;
  86568. },
  86569. /**
  86570. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86571. */
  86572. set: function (value) {
  86573. this.imageProcessingConfiguration.colorGradingTexture = value;
  86574. },
  86575. enumerable: true,
  86576. configurable: true
  86577. });
  86578. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86579. /**
  86580. * Gets wether the color grading effect is enabled.
  86581. */
  86582. get: function () {
  86583. return this.imageProcessingConfiguration.colorGradingEnabled;
  86584. },
  86585. /**
  86586. * Gets wether the color grading effect is enabled.
  86587. */
  86588. set: function (value) {
  86589. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86590. },
  86591. enumerable: true,
  86592. configurable: true
  86593. });
  86594. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86595. /**
  86596. * Gets exposure used in the effect.
  86597. */
  86598. get: function () {
  86599. return this.imageProcessingConfiguration.exposure;
  86600. },
  86601. /**
  86602. * Sets exposure used in the effect.
  86603. */
  86604. set: function (value) {
  86605. this.imageProcessingConfiguration.exposure = value;
  86606. },
  86607. enumerable: true,
  86608. configurable: true
  86609. });
  86610. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86611. /**
  86612. * Gets wether tonemapping is enabled or not.
  86613. */
  86614. get: function () {
  86615. return this._imageProcessingConfiguration.toneMappingEnabled;
  86616. },
  86617. /**
  86618. * Sets wether tonemapping is enabled or not
  86619. */
  86620. set: function (value) {
  86621. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86622. },
  86623. enumerable: true,
  86624. configurable: true
  86625. });
  86626. ;
  86627. ;
  86628. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  86629. /**
  86630. * Gets contrast used in the effect.
  86631. */
  86632. get: function () {
  86633. return this.imageProcessingConfiguration.contrast;
  86634. },
  86635. /**
  86636. * Sets contrast used in the effect.
  86637. */
  86638. set: function (value) {
  86639. this.imageProcessingConfiguration.contrast = value;
  86640. },
  86641. enumerable: true,
  86642. configurable: true
  86643. });
  86644. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  86645. /**
  86646. * Gets Vignette stretch size.
  86647. */
  86648. get: function () {
  86649. return this.imageProcessingConfiguration.vignetteStretch;
  86650. },
  86651. /**
  86652. * Sets Vignette stretch size.
  86653. */
  86654. set: function (value) {
  86655. this.imageProcessingConfiguration.vignetteStretch = value;
  86656. },
  86657. enumerable: true,
  86658. configurable: true
  86659. });
  86660. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  86661. /**
  86662. * Gets Vignette centre X Offset.
  86663. */
  86664. get: function () {
  86665. return this.imageProcessingConfiguration.vignetteCentreX;
  86666. },
  86667. /**
  86668. * Sets Vignette centre X Offset.
  86669. */
  86670. set: function (value) {
  86671. this.imageProcessingConfiguration.vignetteCentreX = value;
  86672. },
  86673. enumerable: true,
  86674. configurable: true
  86675. });
  86676. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  86677. /**
  86678. * Gets Vignette centre Y Offset.
  86679. */
  86680. get: function () {
  86681. return this.imageProcessingConfiguration.vignetteCentreY;
  86682. },
  86683. /**
  86684. * Sets Vignette centre Y Offset.
  86685. */
  86686. set: function (value) {
  86687. this.imageProcessingConfiguration.vignetteCentreY = value;
  86688. },
  86689. enumerable: true,
  86690. configurable: true
  86691. });
  86692. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  86693. /**
  86694. * Gets Vignette weight or intensity of the vignette effect.
  86695. */
  86696. get: function () {
  86697. return this.imageProcessingConfiguration.vignetteWeight;
  86698. },
  86699. /**
  86700. * Sets Vignette weight or intensity of the vignette effect.
  86701. */
  86702. set: function (value) {
  86703. this.imageProcessingConfiguration.vignetteWeight = value;
  86704. },
  86705. enumerable: true,
  86706. configurable: true
  86707. });
  86708. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  86709. /**
  86710. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86711. * if vignetteEnabled is set to true.
  86712. */
  86713. get: function () {
  86714. return this.imageProcessingConfiguration.vignetteColor;
  86715. },
  86716. /**
  86717. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86718. * if vignetteEnabled is set to true.
  86719. */
  86720. set: function (value) {
  86721. this.imageProcessingConfiguration.vignetteColor = value;
  86722. },
  86723. enumerable: true,
  86724. configurable: true
  86725. });
  86726. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  86727. /**
  86728. * Gets Camera field of view used by the Vignette effect.
  86729. */
  86730. get: function () {
  86731. return this.imageProcessingConfiguration.vignetteCameraFov;
  86732. },
  86733. /**
  86734. * Sets Camera field of view used by the Vignette effect.
  86735. */
  86736. set: function (value) {
  86737. this.imageProcessingConfiguration.vignetteCameraFov = value;
  86738. },
  86739. enumerable: true,
  86740. configurable: true
  86741. });
  86742. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  86743. /**
  86744. * Gets the vignette blend mode allowing different kind of effect.
  86745. */
  86746. get: function () {
  86747. return this.imageProcessingConfiguration.vignetteBlendMode;
  86748. },
  86749. /**
  86750. * Sets the vignette blend mode allowing different kind of effect.
  86751. */
  86752. set: function (value) {
  86753. this.imageProcessingConfiguration.vignetteBlendMode = value;
  86754. },
  86755. enumerable: true,
  86756. configurable: true
  86757. });
  86758. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  86759. /**
  86760. * Gets wether the vignette effect is enabled.
  86761. */
  86762. get: function () {
  86763. return this.imageProcessingConfiguration.vignetteEnabled;
  86764. },
  86765. /**
  86766. * Sets wether the vignette effect is enabled.
  86767. */
  86768. set: function (value) {
  86769. this.imageProcessingConfiguration.vignetteEnabled = value;
  86770. },
  86771. enumerable: true,
  86772. configurable: true
  86773. });
  86774. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  86775. /**
  86776. * Gets wether the input of the processing is in Gamma or Linear Space.
  86777. */
  86778. get: function () {
  86779. return this._fromLinearSpace;
  86780. },
  86781. /**
  86782. * Sets wether the input of the processing is in Gamma or Linear Space.
  86783. */
  86784. set: function (value) {
  86785. if (this._fromLinearSpace === value) {
  86786. return;
  86787. }
  86788. this._fromLinearSpace = value;
  86789. this._updateParameters();
  86790. },
  86791. enumerable: true,
  86792. configurable: true
  86793. });
  86794. ImageProcessingPostProcess.prototype.getClassName = function () {
  86795. return "ImageProcessingPostProcess";
  86796. };
  86797. ImageProcessingPostProcess.prototype._updateParameters = function () {
  86798. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  86799. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  86800. var defines = "";
  86801. for (var define in this._defines) {
  86802. if (this._defines[define]) {
  86803. defines += "#define " + define + ";\r\n";
  86804. }
  86805. }
  86806. var samplers = ["textureSampler"];
  86807. var uniforms = ["scale"];
  86808. if (BABYLON.ImageProcessingConfiguration) {
  86809. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  86810. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  86811. }
  86812. this.updateEffect(defines, uniforms, samplers);
  86813. };
  86814. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  86815. _super.prototype.dispose.call(this, camera);
  86816. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86817. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86818. }
  86819. if (this._imageProcessingConfiguration) {
  86820. this.imageProcessingConfiguration.applyByPostProcess = false;
  86821. }
  86822. };
  86823. __decorate([
  86824. BABYLON.serialize()
  86825. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  86826. return ImageProcessingPostProcess;
  86827. }(BABYLON.PostProcess));
  86828. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  86829. })(BABYLON || (BABYLON = {}));
  86830. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  86831. var BABYLON;
  86832. (function (BABYLON) {
  86833. /**
  86834. * Class used to store bone information
  86835. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86836. */
  86837. var Bone = /** @class */ (function (_super) {
  86838. __extends(Bone, _super);
  86839. /**
  86840. * Create a new bone
  86841. * @param name defines the bone name
  86842. * @param skeleton defines the parent skeleton
  86843. * @param parentBone defines the parent (can be null if the bone is the root)
  86844. * @param localMatrix defines the local matrix
  86845. * @param restPose defines the rest pose matrix
  86846. * @param baseMatrix defines the base matrix
  86847. * @param index defines index of the bone in the hiearchy
  86848. */
  86849. function Bone(
  86850. /**
  86851. * defines the bone name
  86852. */
  86853. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  86854. if (parentBone === void 0) { parentBone = null; }
  86855. if (localMatrix === void 0) { localMatrix = null; }
  86856. if (restPose === void 0) { restPose = null; }
  86857. if (baseMatrix === void 0) { baseMatrix = null; }
  86858. if (index === void 0) { index = null; }
  86859. var _this = _super.call(this, name, skeleton.getScene()) || this;
  86860. _this.name = name;
  86861. /**
  86862. * Gets the list of child bones
  86863. */
  86864. _this.children = new Array();
  86865. /** Gets the animations associated with this bone */
  86866. _this.animations = new Array();
  86867. /**
  86868. * @hidden Internal only
  86869. * Set this value to map this bone to a different index in the transform matrices
  86870. * Set this value to -1 to exclude the bone from the transform matrices
  86871. */
  86872. _this._index = null;
  86873. _this._absoluteTransform = new BABYLON.Matrix();
  86874. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  86875. _this._scalingDeterminant = 1;
  86876. _this._worldTransform = new BABYLON.Matrix();
  86877. _this._needToDecompose = true;
  86878. _this._needToCompose = false;
  86879. _this._skeleton = skeleton;
  86880. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86881. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86882. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86883. _this._index = index;
  86884. skeleton.bones.push(_this);
  86885. _this.setParent(parentBone, false);
  86886. if (baseMatrix || localMatrix) {
  86887. _this._updateDifferenceMatrix();
  86888. }
  86889. return _this;
  86890. }
  86891. Object.defineProperty(Bone.prototype, "_matrix", {
  86892. /** @hidden */
  86893. get: function () {
  86894. this._compose();
  86895. return this._localMatrix;
  86896. },
  86897. /** @hidden */
  86898. set: function (value) {
  86899. this._localMatrix.copyFrom(value);
  86900. this._needToDecompose = true;
  86901. },
  86902. enumerable: true,
  86903. configurable: true
  86904. });
  86905. // Members
  86906. /**
  86907. * Gets the parent skeleton
  86908. * @returns a skeleton
  86909. */
  86910. Bone.prototype.getSkeleton = function () {
  86911. return this._skeleton;
  86912. };
  86913. /**
  86914. * Gets parent bone
  86915. * @returns a bone or null if the bone is the root of the bone hierarchy
  86916. */
  86917. Bone.prototype.getParent = function () {
  86918. return this._parent;
  86919. };
  86920. /**
  86921. * Sets the parent bone
  86922. * @param parent defines the parent (can be null if the bone is the root)
  86923. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86924. */
  86925. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86926. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86927. if (this._parent === parent) {
  86928. return;
  86929. }
  86930. if (this._parent) {
  86931. var index = this._parent.children.indexOf(this);
  86932. if (index !== -1) {
  86933. this._parent.children.splice(index, 1);
  86934. }
  86935. }
  86936. this._parent = parent;
  86937. if (this._parent) {
  86938. this._parent.children.push(this);
  86939. }
  86940. if (updateDifferenceMatrix) {
  86941. this._updateDifferenceMatrix();
  86942. }
  86943. this.markAsDirty();
  86944. };
  86945. /**
  86946. * Gets the local matrix
  86947. * @returns a matrix
  86948. */
  86949. Bone.prototype.getLocalMatrix = function () {
  86950. this._compose();
  86951. return this._localMatrix;
  86952. };
  86953. /**
  86954. * Gets the base matrix (initial matrix which remains unchanged)
  86955. * @returns a matrix
  86956. */
  86957. Bone.prototype.getBaseMatrix = function () {
  86958. return this._baseMatrix;
  86959. };
  86960. /**
  86961. * Gets the rest pose matrix
  86962. * @returns a matrix
  86963. */
  86964. Bone.prototype.getRestPose = function () {
  86965. return this._restPose;
  86966. };
  86967. /**
  86968. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86969. */
  86970. Bone.prototype.getWorldMatrix = function () {
  86971. return this._worldTransform;
  86972. };
  86973. /**
  86974. * Sets the local matrix to rest pose matrix
  86975. */
  86976. Bone.prototype.returnToRest = function () {
  86977. this.updateMatrix(this._restPose.clone());
  86978. };
  86979. /**
  86980. * Gets the inverse of the absolute transform matrix.
  86981. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  86982. * @returns a matrix
  86983. */
  86984. Bone.prototype.getInvertedAbsoluteTransform = function () {
  86985. return this._invertedAbsoluteTransform;
  86986. };
  86987. /**
  86988. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  86989. * @returns a matrix
  86990. */
  86991. Bone.prototype.getAbsoluteTransform = function () {
  86992. return this._absoluteTransform;
  86993. };
  86994. Object.defineProperty(Bone.prototype, "position", {
  86995. // Properties (matches AbstractMesh properties)
  86996. /** Gets or sets current position (in local space) */
  86997. get: function () {
  86998. this._decompose();
  86999. return this._localPosition;
  87000. },
  87001. set: function (newPosition) {
  87002. this._decompose();
  87003. this._localPosition.copyFrom(newPosition);
  87004. this._markAsDirtyAndCompose();
  87005. },
  87006. enumerable: true,
  87007. configurable: true
  87008. });
  87009. Object.defineProperty(Bone.prototype, "rotation", {
  87010. /** Gets or sets current rotation (in local space) */
  87011. get: function () {
  87012. return this.getRotation();
  87013. },
  87014. set: function (newRotation) {
  87015. this.setRotation(newRotation);
  87016. },
  87017. enumerable: true,
  87018. configurable: true
  87019. });
  87020. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  87021. /** Gets or sets current rotation quaternion (in local space) */
  87022. get: function () {
  87023. this._decompose();
  87024. return this._localRotation;
  87025. },
  87026. set: function (newRotation) {
  87027. this.setRotationQuaternion(newRotation);
  87028. },
  87029. enumerable: true,
  87030. configurable: true
  87031. });
  87032. Object.defineProperty(Bone.prototype, "scaling", {
  87033. /** Gets or sets current scaling (in local space) */
  87034. get: function () {
  87035. return this.getScale();
  87036. },
  87037. set: function (newScaling) {
  87038. this.setScale(newScaling);
  87039. },
  87040. enumerable: true,
  87041. configurable: true
  87042. });
  87043. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  87044. /**
  87045. * Gets the animation properties override
  87046. */
  87047. get: function () {
  87048. return this._skeleton.animationPropertiesOverride;
  87049. },
  87050. enumerable: true,
  87051. configurable: true
  87052. });
  87053. // Methods
  87054. Bone.prototype._decompose = function () {
  87055. if (!this._needToDecompose) {
  87056. return;
  87057. }
  87058. this._needToDecompose = false;
  87059. if (!this._localScaling) {
  87060. this._localScaling = BABYLON.Vector3.Zero();
  87061. this._localRotation = BABYLON.Quaternion.Zero();
  87062. this._localPosition = BABYLON.Vector3.Zero();
  87063. }
  87064. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  87065. };
  87066. Bone.prototype._compose = function () {
  87067. if (!this._needToCompose) {
  87068. return;
  87069. }
  87070. this._needToCompose = false;
  87071. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  87072. };
  87073. /**
  87074. * Update the base and local matrices
  87075. * @param matrix defines the new base or local matrix
  87076. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87077. * @param updateLocalMatrix defines if the local matrix should be updated
  87078. */
  87079. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  87080. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87081. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  87082. this._baseMatrix.copyFrom(matrix);
  87083. if (updateDifferenceMatrix) {
  87084. this._updateDifferenceMatrix();
  87085. }
  87086. if (updateLocalMatrix) {
  87087. this._localMatrix.copyFrom(matrix);
  87088. this._markAsDirtyAndDecompose();
  87089. }
  87090. else {
  87091. this.markAsDirty();
  87092. }
  87093. };
  87094. /** @hidden */
  87095. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  87096. if (updateChildren === void 0) { updateChildren = true; }
  87097. if (!rootMatrix) {
  87098. rootMatrix = this._baseMatrix;
  87099. }
  87100. if (this._parent) {
  87101. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87102. }
  87103. else {
  87104. this._absoluteTransform.copyFrom(rootMatrix);
  87105. }
  87106. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  87107. if (updateChildren) {
  87108. for (var index = 0; index < this.children.length; index++) {
  87109. this.children[index]._updateDifferenceMatrix();
  87110. }
  87111. }
  87112. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  87113. };
  87114. /**
  87115. * Flag the bone as dirty (Forcing it to update everything)
  87116. */
  87117. Bone.prototype.markAsDirty = function () {
  87118. this._currentRenderId++;
  87119. this._childRenderId++;
  87120. this._skeleton._markAsDirty();
  87121. };
  87122. Bone.prototype._markAsDirtyAndCompose = function () {
  87123. this.markAsDirty();
  87124. this._needToCompose = true;
  87125. };
  87126. Bone.prototype._markAsDirtyAndDecompose = function () {
  87127. this.markAsDirty();
  87128. this._needToDecompose = true;
  87129. };
  87130. /**
  87131. * Copy an animation range from another bone
  87132. * @param source defines the source bone
  87133. * @param rangeName defines the range name to copy
  87134. * @param frameOffset defines the frame offset
  87135. * @param rescaleAsRequired defines if rescaling must be applied if required
  87136. * @param skelDimensionsRatio defines the scaling ratio
  87137. * @returns true if operation was successful
  87138. */
  87139. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  87140. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87141. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  87142. // all animation may be coming from a library skeleton, so may need to create animation
  87143. if (this.animations.length === 0) {
  87144. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  87145. this.animations[0].setKeys([]);
  87146. }
  87147. // get animation info / verify there is such a range from the source bone
  87148. var sourceRange = source.animations[0].getRange(rangeName);
  87149. if (!sourceRange) {
  87150. return false;
  87151. }
  87152. var from = sourceRange.from;
  87153. var to = sourceRange.to;
  87154. var sourceKeys = source.animations[0].getKeys();
  87155. // rescaling prep
  87156. var sourceBoneLength = source.length;
  87157. var sourceParent = source.getParent();
  87158. var parent = this.getParent();
  87159. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  87160. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  87161. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  87162. var destKeys = this.animations[0].getKeys();
  87163. // loop vars declaration
  87164. var orig;
  87165. var origTranslation;
  87166. var mat;
  87167. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  87168. orig = sourceKeys[key];
  87169. if (orig.frame >= from && orig.frame <= to) {
  87170. if (rescaleAsRequired) {
  87171. mat = orig.value.clone();
  87172. // scale based on parent ratio, when bone has parent
  87173. if (parentScalingReqd) {
  87174. origTranslation = mat.getTranslation();
  87175. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  87176. // scale based on skeleton dimension ratio when root bone, and value is passed
  87177. }
  87178. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  87179. origTranslation = mat.getTranslation();
  87180. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  87181. // use original when root bone, and no data for skelDimensionsRatio
  87182. }
  87183. else {
  87184. mat = orig.value;
  87185. }
  87186. }
  87187. else {
  87188. mat = orig.value;
  87189. }
  87190. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  87191. }
  87192. }
  87193. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  87194. return true;
  87195. };
  87196. /**
  87197. * Translate the bone in local or world space
  87198. * @param vec The amount to translate the bone
  87199. * @param space The space that the translation is in
  87200. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87201. */
  87202. Bone.prototype.translate = function (vec, space, mesh) {
  87203. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87204. var lm = this.getLocalMatrix();
  87205. if (space == BABYLON.Space.LOCAL) {
  87206. lm.m[12] += vec.x;
  87207. lm.m[13] += vec.y;
  87208. lm.m[14] += vec.z;
  87209. }
  87210. else {
  87211. var wm = null;
  87212. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87213. if (mesh) {
  87214. wm = mesh.getWorldMatrix();
  87215. }
  87216. this._skeleton.computeAbsoluteTransforms();
  87217. var tmat = Bone._tmpMats[0];
  87218. var tvec = Bone._tmpVecs[0];
  87219. if (this._parent) {
  87220. if (mesh && wm) {
  87221. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87222. tmat.multiplyToRef(wm, tmat);
  87223. }
  87224. else {
  87225. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87226. }
  87227. }
  87228. tmat.m[12] = 0;
  87229. tmat.m[13] = 0;
  87230. tmat.m[14] = 0;
  87231. tmat.invert();
  87232. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  87233. lm.m[12] += tvec.x;
  87234. lm.m[13] += tvec.y;
  87235. lm.m[14] += tvec.z;
  87236. }
  87237. this._markAsDirtyAndDecompose();
  87238. };
  87239. /**
  87240. * Set the postion of the bone in local or world space
  87241. * @param position The position to set the bone
  87242. * @param space The space that the position is in
  87243. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87244. */
  87245. Bone.prototype.setPosition = function (position, space, mesh) {
  87246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87247. var lm = this.getLocalMatrix();
  87248. if (space == BABYLON.Space.LOCAL) {
  87249. lm.m[12] = position.x;
  87250. lm.m[13] = position.y;
  87251. lm.m[14] = position.z;
  87252. }
  87253. else {
  87254. var wm = null;
  87255. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87256. if (mesh) {
  87257. wm = mesh.getWorldMatrix();
  87258. }
  87259. this._skeleton.computeAbsoluteTransforms();
  87260. var tmat = Bone._tmpMats[0];
  87261. var vec = Bone._tmpVecs[0];
  87262. if (this._parent) {
  87263. if (mesh && wm) {
  87264. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87265. tmat.multiplyToRef(wm, tmat);
  87266. }
  87267. else {
  87268. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87269. }
  87270. }
  87271. tmat.invert();
  87272. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  87273. lm.m[12] = vec.x;
  87274. lm.m[13] = vec.y;
  87275. lm.m[14] = vec.z;
  87276. }
  87277. this._markAsDirtyAndDecompose();
  87278. };
  87279. /**
  87280. * Set the absolute position of the bone (world space)
  87281. * @param position The position to set the bone
  87282. * @param mesh The mesh that this bone is attached to
  87283. */
  87284. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  87285. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  87286. };
  87287. /**
  87288. * Scale the bone on the x, y and z axes (in local space)
  87289. * @param x The amount to scale the bone on the x axis
  87290. * @param y The amount to scale the bone on the y axis
  87291. * @param z The amount to scale the bone on the z axis
  87292. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  87293. */
  87294. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  87295. if (scaleChildren === void 0) { scaleChildren = false; }
  87296. var locMat = this.getLocalMatrix();
  87297. // Apply new scaling on top of current local matrix
  87298. var scaleMat = Bone._tmpMats[0];
  87299. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  87300. scaleMat.multiplyToRef(locMat, locMat);
  87301. // Invert scaling matrix and apply the inverse to all children
  87302. scaleMat.invert();
  87303. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  87304. var child = _a[_i];
  87305. var cm = child.getLocalMatrix();
  87306. cm.multiplyToRef(scaleMat, cm);
  87307. cm.m[12] *= x;
  87308. cm.m[13] *= y;
  87309. cm.m[14] *= z;
  87310. child._markAsDirtyAndDecompose();
  87311. }
  87312. this._markAsDirtyAndDecompose();
  87313. if (scaleChildren) {
  87314. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  87315. var child = _c[_b];
  87316. child.scale(x, y, z, scaleChildren);
  87317. }
  87318. }
  87319. };
  87320. /**
  87321. * Set the bone scaling in local space
  87322. * @param scale defines the scaling vector
  87323. */
  87324. Bone.prototype.setScale = function (scale) {
  87325. this._decompose();
  87326. this._localScaling.copyFrom(scale);
  87327. this._markAsDirtyAndCompose();
  87328. };
  87329. /**
  87330. * Gets the current scaling in local space
  87331. * @returns the current scaling vector
  87332. */
  87333. Bone.prototype.getScale = function () {
  87334. this._decompose();
  87335. return this._localScaling;
  87336. };
  87337. /**
  87338. * Gets the current scaling in local space and stores it in a target vector
  87339. * @param result defines the target vector
  87340. */
  87341. Bone.prototype.getScaleToRef = function (result) {
  87342. this._decompose();
  87343. result.copyFrom(this._localScaling);
  87344. };
  87345. /**
  87346. * Set the yaw, pitch, and roll of the bone in local or world space
  87347. * @param yaw The rotation of the bone on the y axis
  87348. * @param pitch The rotation of the bone on the x axis
  87349. * @param roll The rotation of the bone on the z axis
  87350. * @param space The space that the axes of rotation are in
  87351. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87352. */
  87353. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  87354. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87355. if (space === BABYLON.Space.LOCAL) {
  87356. var quat = Bone._tmpQuat;
  87357. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  87358. this.setRotationQuaternion(quat, space, mesh);
  87359. return;
  87360. }
  87361. var rotMatInv = Bone._tmpMats[0];
  87362. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87363. return;
  87364. }
  87365. var rotMat = Bone._tmpMats[1];
  87366. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  87367. rotMatInv.multiplyToRef(rotMat, rotMat);
  87368. this._rotateWithMatrix(rotMat, space, mesh);
  87369. };
  87370. /**
  87371. * Add a rotation to the bone on an axis in local or world space
  87372. * @param axis The axis to rotate the bone on
  87373. * @param amount The amount to rotate the bone
  87374. * @param space The space that the axis is in
  87375. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87376. */
  87377. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  87378. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87379. var rmat = Bone._tmpMats[0];
  87380. rmat.m[12] = 0;
  87381. rmat.m[13] = 0;
  87382. rmat.m[14] = 0;
  87383. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  87384. this._rotateWithMatrix(rmat, space, mesh);
  87385. };
  87386. /**
  87387. * Set the rotation of the bone to a particular axis angle in local or world space
  87388. * @param axis The axis to rotate the bone on
  87389. * @param angle The angle that the bone should be rotated to
  87390. * @param space The space that the axis is in
  87391. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87392. */
  87393. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  87394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87395. if (space === BABYLON.Space.LOCAL) {
  87396. var quat = Bone._tmpQuat;
  87397. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  87398. this.setRotationQuaternion(quat, space, mesh);
  87399. return;
  87400. }
  87401. var rotMatInv = Bone._tmpMats[0];
  87402. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87403. return;
  87404. }
  87405. var rotMat = Bone._tmpMats[1];
  87406. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  87407. rotMatInv.multiplyToRef(rotMat, rotMat);
  87408. this._rotateWithMatrix(rotMat, space, mesh);
  87409. };
  87410. /**
  87411. * Set the euler rotation of the bone in local of world space
  87412. * @param rotation The euler rotation that the bone should be set to
  87413. * @param space The space that the rotation is in
  87414. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87415. */
  87416. Bone.prototype.setRotation = function (rotation, space, mesh) {
  87417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87418. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  87419. };
  87420. /**
  87421. * Set the quaternion rotation of the bone in local of world space
  87422. * @param quat The quaternion rotation that the bone should be set to
  87423. * @param space The space that the rotation is in
  87424. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87425. */
  87426. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  87427. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87428. if (space === BABYLON.Space.LOCAL) {
  87429. this._decompose();
  87430. this._localRotation.copyFrom(quat);
  87431. this._markAsDirtyAndCompose();
  87432. return;
  87433. }
  87434. var rotMatInv = Bone._tmpMats[0];
  87435. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87436. return;
  87437. }
  87438. var rotMat = Bone._tmpMats[1];
  87439. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  87440. rotMatInv.multiplyToRef(rotMat, rotMat);
  87441. this._rotateWithMatrix(rotMat, space, mesh);
  87442. };
  87443. /**
  87444. * Set the rotation matrix of the bone in local of world space
  87445. * @param rotMat The rotation matrix that the bone should be set to
  87446. * @param space The space that the rotation is in
  87447. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87448. */
  87449. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  87450. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87451. if (space === BABYLON.Space.LOCAL) {
  87452. var quat = Bone._tmpQuat;
  87453. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  87454. this.setRotationQuaternion(quat, space, mesh);
  87455. return;
  87456. }
  87457. var rotMatInv = Bone._tmpMats[0];
  87458. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87459. return;
  87460. }
  87461. var rotMat2 = Bone._tmpMats[1];
  87462. rotMat2.copyFrom(rotMat);
  87463. rotMatInv.multiplyToRef(rotMat, rotMat2);
  87464. this._rotateWithMatrix(rotMat2, space, mesh);
  87465. };
  87466. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  87467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87468. var lmat = this.getLocalMatrix();
  87469. var lx = lmat.m[12];
  87470. var ly = lmat.m[13];
  87471. var lz = lmat.m[14];
  87472. var parent = this.getParent();
  87473. var parentScale = Bone._tmpMats[3];
  87474. var parentScaleInv = Bone._tmpMats[4];
  87475. if (parent && space == BABYLON.Space.WORLD) {
  87476. if (mesh) {
  87477. parentScale.copyFrom(mesh.getWorldMatrix());
  87478. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  87479. }
  87480. else {
  87481. parentScale.copyFrom(parent.getAbsoluteTransform());
  87482. }
  87483. parentScaleInv.copyFrom(parentScale);
  87484. parentScaleInv.invert();
  87485. lmat.multiplyToRef(parentScale, lmat);
  87486. lmat.multiplyToRef(rmat, lmat);
  87487. lmat.multiplyToRef(parentScaleInv, lmat);
  87488. }
  87489. else {
  87490. if (space == BABYLON.Space.WORLD && mesh) {
  87491. parentScale.copyFrom(mesh.getWorldMatrix());
  87492. parentScaleInv.copyFrom(parentScale);
  87493. parentScaleInv.invert();
  87494. lmat.multiplyToRef(parentScale, lmat);
  87495. lmat.multiplyToRef(rmat, lmat);
  87496. lmat.multiplyToRef(parentScaleInv, lmat);
  87497. }
  87498. else {
  87499. lmat.multiplyToRef(rmat, lmat);
  87500. }
  87501. }
  87502. lmat.m[12] = lx;
  87503. lmat.m[13] = ly;
  87504. lmat.m[14] = lz;
  87505. this.computeAbsoluteTransforms();
  87506. this._markAsDirtyAndDecompose();
  87507. };
  87508. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  87509. var scaleMatrix = Bone._tmpMats[2];
  87510. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87511. if (mesh) {
  87512. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87513. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87514. }
  87515. rotMatInv.invert();
  87516. if (isNaN(rotMatInv.m[0])) {
  87517. // Matrix failed to invert.
  87518. // This can happen if scale is zero for example.
  87519. return false;
  87520. }
  87521. scaleMatrix.m[0] *= this._scalingDeterminant;
  87522. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87523. return true;
  87524. };
  87525. /**
  87526. * Get the position of the bone in local or world space
  87527. * @param space The space that the returned position is in
  87528. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87529. * @returns The position of the bone
  87530. */
  87531. Bone.prototype.getPosition = function (space, mesh) {
  87532. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87533. if (mesh === void 0) { mesh = null; }
  87534. var pos = BABYLON.Vector3.Zero();
  87535. this.getPositionToRef(space, mesh, pos);
  87536. return pos;
  87537. };
  87538. /**
  87539. * Copy the position of the bone to a vector3 in local or world space
  87540. * @param space The space that the returned position is in
  87541. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87542. * @param result The vector3 to copy the position to
  87543. */
  87544. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87546. if (space == BABYLON.Space.LOCAL) {
  87547. var lm = this.getLocalMatrix();
  87548. result.x = lm.m[12];
  87549. result.y = lm.m[13];
  87550. result.z = lm.m[14];
  87551. }
  87552. else {
  87553. var wm = null;
  87554. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87555. if (mesh) {
  87556. wm = mesh.getWorldMatrix();
  87557. }
  87558. this._skeleton.computeAbsoluteTransforms();
  87559. var tmat = Bone._tmpMats[0];
  87560. if (mesh && wm) {
  87561. tmat.copyFrom(this.getAbsoluteTransform());
  87562. tmat.multiplyToRef(wm, tmat);
  87563. }
  87564. else {
  87565. tmat = this.getAbsoluteTransform();
  87566. }
  87567. result.x = tmat.m[12];
  87568. result.y = tmat.m[13];
  87569. result.z = tmat.m[14];
  87570. }
  87571. };
  87572. /**
  87573. * Get the absolute position of the bone (world space)
  87574. * @param mesh The mesh that this bone is attached to
  87575. * @returns The absolute position of the bone
  87576. */
  87577. Bone.prototype.getAbsolutePosition = function (mesh) {
  87578. if (mesh === void 0) { mesh = null; }
  87579. var pos = BABYLON.Vector3.Zero();
  87580. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87581. return pos;
  87582. };
  87583. /**
  87584. * Copy the absolute position of the bone (world space) to the result param
  87585. * @param mesh The mesh that this bone is attached to
  87586. * @param result The vector3 to copy the absolute position to
  87587. */
  87588. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87589. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87590. };
  87591. /**
  87592. * Compute the absolute transforms of this bone and its children
  87593. */
  87594. Bone.prototype.computeAbsoluteTransforms = function () {
  87595. this._compose();
  87596. if (this._parent) {
  87597. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87598. }
  87599. else {
  87600. this._absoluteTransform.copyFrom(this._localMatrix);
  87601. var poseMatrix = this._skeleton.getPoseMatrix();
  87602. if (poseMatrix) {
  87603. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87604. }
  87605. }
  87606. var children = this.children;
  87607. var len = children.length;
  87608. for (var i = 0; i < len; i++) {
  87609. children[i].computeAbsoluteTransforms();
  87610. }
  87611. };
  87612. /**
  87613. * Get the world direction from an axis that is in the local space of the bone
  87614. * @param localAxis The local direction that is used to compute the world direction
  87615. * @param mesh The mesh that this bone is attached to
  87616. * @returns The world direction
  87617. */
  87618. Bone.prototype.getDirection = function (localAxis, mesh) {
  87619. if (mesh === void 0) { mesh = null; }
  87620. var result = BABYLON.Vector3.Zero();
  87621. this.getDirectionToRef(localAxis, mesh, result);
  87622. return result;
  87623. };
  87624. /**
  87625. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  87626. * @param localAxis The local direction that is used to compute the world direction
  87627. * @param mesh The mesh that this bone is attached to
  87628. * @param result The vector3 that the world direction will be copied to
  87629. */
  87630. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  87631. if (mesh === void 0) { mesh = null; }
  87632. var wm = null;
  87633. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87634. if (mesh) {
  87635. wm = mesh.getWorldMatrix();
  87636. }
  87637. this._skeleton.computeAbsoluteTransforms();
  87638. var mat = Bone._tmpMats[0];
  87639. mat.copyFrom(this.getAbsoluteTransform());
  87640. if (mesh && wm) {
  87641. mat.multiplyToRef(wm, mat);
  87642. }
  87643. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  87644. result.normalize();
  87645. };
  87646. /**
  87647. * Get the euler rotation of the bone in local or world space
  87648. * @param space The space that the rotation should be in
  87649. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87650. * @returns The euler rotation
  87651. */
  87652. Bone.prototype.getRotation = function (space, mesh) {
  87653. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87654. if (mesh === void 0) { mesh = null; }
  87655. var result = BABYLON.Vector3.Zero();
  87656. this.getRotationToRef(space, mesh, result);
  87657. return result;
  87658. };
  87659. /**
  87660. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  87661. * @param space The space that the rotation should be in
  87662. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87663. * @param result The vector3 that the rotation should be copied to
  87664. */
  87665. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  87666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87667. if (mesh === void 0) { mesh = null; }
  87668. var quat = Bone._tmpQuat;
  87669. this.getRotationQuaternionToRef(space, mesh, quat);
  87670. quat.toEulerAnglesToRef(result);
  87671. };
  87672. /**
  87673. * Get the quaternion rotation of the bone in either local or world space
  87674. * @param space The space that the rotation should be in
  87675. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87676. * @returns The quaternion rotation
  87677. */
  87678. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  87679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87680. if (mesh === void 0) { mesh = null; }
  87681. var result = BABYLON.Quaternion.Identity();
  87682. this.getRotationQuaternionToRef(space, mesh, result);
  87683. return result;
  87684. };
  87685. /**
  87686. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  87687. * @param space The space that the rotation should be in
  87688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87689. * @param result The quaternion that the rotation should be copied to
  87690. */
  87691. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  87692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87693. if (mesh === void 0) { mesh = null; }
  87694. if (space == BABYLON.Space.LOCAL) {
  87695. this._decompose();
  87696. result.copyFrom(this._localRotation);
  87697. }
  87698. else {
  87699. var mat = Bone._tmpMats[0];
  87700. var amat = this.getAbsoluteTransform();
  87701. if (mesh) {
  87702. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87703. }
  87704. else {
  87705. mat.copyFrom(amat);
  87706. }
  87707. mat.m[0] *= this._scalingDeterminant;
  87708. mat.m[1] *= this._scalingDeterminant;
  87709. mat.m[2] *= this._scalingDeterminant;
  87710. mat.decompose(undefined, result, undefined);
  87711. }
  87712. };
  87713. /**
  87714. * Get the rotation matrix of the bone in local or world space
  87715. * @param space The space that the rotation should be in
  87716. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87717. * @returns The rotation matrix
  87718. */
  87719. Bone.prototype.getRotationMatrix = function (space, mesh) {
  87720. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87721. var result = BABYLON.Matrix.Identity();
  87722. this.getRotationMatrixToRef(space, mesh, result);
  87723. return result;
  87724. };
  87725. /**
  87726. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  87727. * @param space The space that the rotation should be in
  87728. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87729. * @param result The quaternion that the rotation should be copied to
  87730. */
  87731. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  87732. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87733. if (space == BABYLON.Space.LOCAL) {
  87734. this.getLocalMatrix().getRotationMatrixToRef(result);
  87735. }
  87736. else {
  87737. var mat = Bone._tmpMats[0];
  87738. var amat = this.getAbsoluteTransform();
  87739. if (mesh) {
  87740. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87741. }
  87742. else {
  87743. mat.copyFrom(amat);
  87744. }
  87745. mat.m[0] *= this._scalingDeterminant;
  87746. mat.m[1] *= this._scalingDeterminant;
  87747. mat.m[2] *= this._scalingDeterminant;
  87748. mat.getRotationMatrixToRef(result);
  87749. }
  87750. };
  87751. /**
  87752. * Get the world position of a point that is in the local space of the bone
  87753. * @param position The local position
  87754. * @param mesh The mesh that this bone is attached to
  87755. * @returns The world position
  87756. */
  87757. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  87758. if (mesh === void 0) { mesh = null; }
  87759. var result = BABYLON.Vector3.Zero();
  87760. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  87761. return result;
  87762. };
  87763. /**
  87764. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  87765. * @param position The local position
  87766. * @param mesh The mesh that this bone is attached to
  87767. * @param result The vector3 that the world position should be copied to
  87768. */
  87769. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  87770. if (mesh === void 0) { mesh = null; }
  87771. var wm = null;
  87772. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87773. if (mesh) {
  87774. wm = mesh.getWorldMatrix();
  87775. }
  87776. this._skeleton.computeAbsoluteTransforms();
  87777. var tmat = Bone._tmpMats[0];
  87778. if (mesh && wm) {
  87779. tmat.copyFrom(this.getAbsoluteTransform());
  87780. tmat.multiplyToRef(wm, tmat);
  87781. }
  87782. else {
  87783. tmat = this.getAbsoluteTransform();
  87784. }
  87785. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87786. };
  87787. /**
  87788. * Get the local position of a point that is in world space
  87789. * @param position The world position
  87790. * @param mesh The mesh that this bone is attached to
  87791. * @returns The local position
  87792. */
  87793. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  87794. if (mesh === void 0) { mesh = null; }
  87795. var result = BABYLON.Vector3.Zero();
  87796. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  87797. return result;
  87798. };
  87799. /**
  87800. * Get the local position of a point that is in world space and copy it to the result param
  87801. * @param position The world position
  87802. * @param mesh The mesh that this bone is attached to
  87803. * @param result The vector3 that the local position should be copied to
  87804. */
  87805. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  87806. if (mesh === void 0) { mesh = null; }
  87807. var wm = null;
  87808. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87809. if (mesh) {
  87810. wm = mesh.getWorldMatrix();
  87811. }
  87812. this._skeleton.computeAbsoluteTransforms();
  87813. var tmat = Bone._tmpMats[0];
  87814. tmat.copyFrom(this.getAbsoluteTransform());
  87815. if (mesh && wm) {
  87816. tmat.multiplyToRef(wm, tmat);
  87817. }
  87818. tmat.invert();
  87819. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87820. };
  87821. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87822. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  87823. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87824. return Bone;
  87825. }(BABYLON.Node));
  87826. BABYLON.Bone = Bone;
  87827. })(BABYLON || (BABYLON = {}));
  87828. //# sourceMappingURL=babylon.bone.js.map
  87829. var BABYLON;
  87830. (function (BABYLON) {
  87831. /**
  87832. * Class used to apply inverse kinematics to bones
  87833. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  87834. */
  87835. var BoneIKController = /** @class */ (function () {
  87836. /**
  87837. * Creates a new BoneIKController
  87838. * @param mesh defines the mesh to control
  87839. * @param bone defines the bone to control
  87840. * @param options defines options to set up the controller
  87841. */
  87842. function BoneIKController(mesh, bone, options) {
  87843. /**
  87844. * Gets or sets the target position
  87845. */
  87846. this.targetPosition = BABYLON.Vector3.Zero();
  87847. /**
  87848. * Gets or sets the pole target position
  87849. */
  87850. this.poleTargetPosition = BABYLON.Vector3.Zero();
  87851. /**
  87852. * Gets or sets the pole target local offset
  87853. */
  87854. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  87855. /**
  87856. * Gets or sets the pole angle
  87857. */
  87858. this.poleAngle = 0;
  87859. /**
  87860. * 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)
  87861. */
  87862. this.slerpAmount = 1;
  87863. this._bone1Quat = BABYLON.Quaternion.Identity();
  87864. this._bone1Mat = BABYLON.Matrix.Identity();
  87865. this._bone2Ang = Math.PI;
  87866. this._maxAngle = Math.PI;
  87867. this._rightHandedSystem = false;
  87868. this._bendAxis = BABYLON.Vector3.Right();
  87869. this._slerping = false;
  87870. this._adjustRoll = 0;
  87871. this._bone2 = bone;
  87872. this._bone1 = bone.getParent();
  87873. if (!this._bone1) {
  87874. return;
  87875. }
  87876. this.mesh = mesh;
  87877. var bonePos = bone.getPosition();
  87878. if (bone.getAbsoluteTransform().determinant() > 0) {
  87879. this._rightHandedSystem = true;
  87880. this._bendAxis.x = 0;
  87881. this._bendAxis.y = 0;
  87882. this._bendAxis.z = -1;
  87883. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87884. this._adjustRoll = Math.PI * .5;
  87885. this._bendAxis.z = 1;
  87886. }
  87887. }
  87888. if (this._bone1.length) {
  87889. var boneScale1 = this._bone1.getScale();
  87890. var boneScale2 = this._bone2.getScale();
  87891. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87892. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87893. }
  87894. else if (this._bone1.children[0]) {
  87895. mesh.computeWorldMatrix(true);
  87896. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87897. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87898. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87899. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87900. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87901. }
  87902. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87903. this.maxAngle = Math.PI;
  87904. if (options) {
  87905. if (options.targetMesh) {
  87906. this.targetMesh = options.targetMesh;
  87907. this.targetMesh.computeWorldMatrix(true);
  87908. }
  87909. if (options.poleTargetMesh) {
  87910. this.poleTargetMesh = options.poleTargetMesh;
  87911. this.poleTargetMesh.computeWorldMatrix(true);
  87912. }
  87913. else if (options.poleTargetBone) {
  87914. this.poleTargetBone = options.poleTargetBone;
  87915. }
  87916. else if (this._bone1.getParent()) {
  87917. this.poleTargetBone = this._bone1.getParent();
  87918. }
  87919. if (options.poleTargetLocalOffset) {
  87920. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87921. }
  87922. if (options.poleAngle) {
  87923. this.poleAngle = options.poleAngle;
  87924. }
  87925. if (options.bendAxis) {
  87926. this._bendAxis.copyFrom(options.bendAxis);
  87927. }
  87928. if (options.maxAngle) {
  87929. this.maxAngle = options.maxAngle;
  87930. }
  87931. if (options.slerpAmount) {
  87932. this.slerpAmount = options.slerpAmount;
  87933. }
  87934. }
  87935. }
  87936. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87937. /**
  87938. * Gets or sets maximum allowed angle
  87939. */
  87940. get: function () {
  87941. return this._maxAngle;
  87942. },
  87943. set: function (value) {
  87944. this._setMaxAngle(value);
  87945. },
  87946. enumerable: true,
  87947. configurable: true
  87948. });
  87949. BoneIKController.prototype._setMaxAngle = function (ang) {
  87950. if (ang < 0) {
  87951. ang = 0;
  87952. }
  87953. if (ang > Math.PI || ang == undefined) {
  87954. ang = Math.PI;
  87955. }
  87956. this._maxAngle = ang;
  87957. var a = this._bone1Length;
  87958. var b = this._bone2Length;
  87959. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87960. };
  87961. /**
  87962. * Force the controller to update the bones
  87963. */
  87964. BoneIKController.prototype.update = function () {
  87965. var bone1 = this._bone1;
  87966. if (!bone1) {
  87967. return;
  87968. }
  87969. var target = this.targetPosition;
  87970. var poleTarget = this.poleTargetPosition;
  87971. var mat1 = BoneIKController._tmpMats[0];
  87972. var mat2 = BoneIKController._tmpMats[1];
  87973. if (this.targetMesh) {
  87974. target.copyFrom(this.targetMesh.getAbsolutePosition());
  87975. }
  87976. if (this.poleTargetBone) {
  87977. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  87978. }
  87979. else if (this.poleTargetMesh) {
  87980. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  87981. }
  87982. var bonePos = BoneIKController._tmpVecs[0];
  87983. var zaxis = BoneIKController._tmpVecs[1];
  87984. var xaxis = BoneIKController._tmpVecs[2];
  87985. var yaxis = BoneIKController._tmpVecs[3];
  87986. var upAxis = BoneIKController._tmpVecs[4];
  87987. var _tmpQuat = BoneIKController._tmpQuat;
  87988. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  87989. poleTarget.subtractToRef(bonePos, upAxis);
  87990. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  87991. upAxis.y = 1;
  87992. }
  87993. else {
  87994. upAxis.normalize();
  87995. }
  87996. target.subtractToRef(bonePos, yaxis);
  87997. yaxis.normalize();
  87998. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  87999. zaxis.normalize();
  88000. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  88001. xaxis.normalize();
  88002. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  88003. var a = this._bone1Length;
  88004. var b = this._bone2Length;
  88005. var c = BABYLON.Vector3.Distance(bonePos, target);
  88006. if (this._maxReach > 0) {
  88007. c = Math.min(this._maxReach, c);
  88008. }
  88009. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  88010. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  88011. if (acosa > 1) {
  88012. acosa = 1;
  88013. }
  88014. if (acosb > 1) {
  88015. acosb = 1;
  88016. }
  88017. if (acosa < -1) {
  88018. acosa = -1;
  88019. }
  88020. if (acosb < -1) {
  88021. acosb = -1;
  88022. }
  88023. var angA = Math.acos(acosa);
  88024. var angB = Math.acos(acosb);
  88025. var angC = -angA - angB;
  88026. if (this._rightHandedSystem) {
  88027. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  88028. mat2.multiplyToRef(mat1, mat1);
  88029. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  88030. mat2.multiplyToRef(mat1, mat1);
  88031. }
  88032. else {
  88033. var _tmpVec = BoneIKController._tmpVecs[5];
  88034. _tmpVec.copyFrom(this._bendAxis);
  88035. _tmpVec.x *= -1;
  88036. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  88037. mat2.multiplyToRef(mat1, mat1);
  88038. }
  88039. if (this.poleAngle) {
  88040. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  88041. mat1.multiplyToRef(mat2, mat1);
  88042. }
  88043. if (this._bone1) {
  88044. if (this.slerpAmount < 1) {
  88045. if (!this._slerping) {
  88046. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  88047. }
  88048. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  88049. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  88050. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  88051. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  88052. this._slerping = true;
  88053. }
  88054. else {
  88055. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  88056. this._bone1Mat.copyFrom(mat1);
  88057. this._slerping = false;
  88058. }
  88059. }
  88060. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  88061. this._bone2Ang = angC;
  88062. };
  88063. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88064. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  88065. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88066. return BoneIKController;
  88067. }());
  88068. BABYLON.BoneIKController = BoneIKController;
  88069. })(BABYLON || (BABYLON = {}));
  88070. //# sourceMappingURL=babylon.boneIKController.js.map
  88071. var BABYLON;
  88072. (function (BABYLON) {
  88073. /**
  88074. * Class used to make a bone look toward a point in space
  88075. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  88076. */
  88077. var BoneLookController = /** @class */ (function () {
  88078. /**
  88079. * Create a BoneLookController
  88080. * @param mesh the mesh that the bone belongs to
  88081. * @param bone the bone that will be looking to the target
  88082. * @param target the target Vector3 to look at
  88083. * @param settings optional settings:
  88084. * * maxYaw: the maximum angle the bone will yaw to
  88085. * * minYaw: the minimum angle the bone will yaw to
  88086. * * maxPitch: the maximum angle the bone will pitch to
  88087. * * minPitch: the minimum angle the bone will yaw to
  88088. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  88089. * * upAxis: the up axis of the coordinate system
  88090. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  88091. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  88092. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  88093. * * adjustYaw: used to make an adjustment to the yaw of the bone
  88094. * * adjustPitch: used to make an adjustment to the pitch of the bone
  88095. * * adjustRoll: used to make an adjustment to the roll of the bone
  88096. **/
  88097. function BoneLookController(mesh, bone, target, options) {
  88098. /**
  88099. * The up axis of the coordinate system that is used when the bone is rotated
  88100. */
  88101. this.upAxis = BABYLON.Vector3.Up();
  88102. /**
  88103. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  88104. */
  88105. this.upAxisSpace = BABYLON.Space.LOCAL;
  88106. /**
  88107. * Used to make an adjustment to the yaw of the bone
  88108. */
  88109. this.adjustYaw = 0;
  88110. /**
  88111. * Used to make an adjustment to the pitch of the bone
  88112. */
  88113. this.adjustPitch = 0;
  88114. /**
  88115. * Used to make an adjustment to the roll of the bone
  88116. */
  88117. this.adjustRoll = 0;
  88118. /**
  88119. * 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)
  88120. */
  88121. this.slerpAmount = 1;
  88122. this._boneQuat = BABYLON.Quaternion.Identity();
  88123. this._slerping = false;
  88124. this._firstFrameSkipped = false;
  88125. this._fowardAxis = BABYLON.Vector3.Forward();
  88126. this.mesh = mesh;
  88127. this.bone = bone;
  88128. this.target = target;
  88129. if (options) {
  88130. if (options.adjustYaw) {
  88131. this.adjustYaw = options.adjustYaw;
  88132. }
  88133. if (options.adjustPitch) {
  88134. this.adjustPitch = options.adjustPitch;
  88135. }
  88136. if (options.adjustRoll) {
  88137. this.adjustRoll = options.adjustRoll;
  88138. }
  88139. if (options.maxYaw != null) {
  88140. this.maxYaw = options.maxYaw;
  88141. }
  88142. else {
  88143. this.maxYaw = Math.PI;
  88144. }
  88145. if (options.minYaw != null) {
  88146. this.minYaw = options.minYaw;
  88147. }
  88148. else {
  88149. this.minYaw = -Math.PI;
  88150. }
  88151. if (options.maxPitch != null) {
  88152. this.maxPitch = options.maxPitch;
  88153. }
  88154. else {
  88155. this.maxPitch = Math.PI;
  88156. }
  88157. if (options.minPitch != null) {
  88158. this.minPitch = options.minPitch;
  88159. }
  88160. else {
  88161. this.minPitch = -Math.PI;
  88162. }
  88163. if (options.slerpAmount != null) {
  88164. this.slerpAmount = options.slerpAmount;
  88165. }
  88166. if (options.upAxis != null) {
  88167. this.upAxis = options.upAxis;
  88168. }
  88169. if (options.upAxisSpace != null) {
  88170. this.upAxisSpace = options.upAxisSpace;
  88171. }
  88172. if (options.yawAxis != null || options.pitchAxis != null) {
  88173. var newYawAxis = BABYLON.Axis.Y;
  88174. var newPitchAxis = BABYLON.Axis.X;
  88175. if (options.yawAxis != null) {
  88176. newYawAxis = options.yawAxis.clone();
  88177. newYawAxis.normalize();
  88178. }
  88179. if (options.pitchAxis != null) {
  88180. newPitchAxis = options.pitchAxis.clone();
  88181. newPitchAxis.normalize();
  88182. }
  88183. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  88184. this._transformYawPitch = BABYLON.Matrix.Identity();
  88185. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  88186. this._transformYawPitchInv = this._transformYawPitch.clone();
  88187. this._transformYawPitch.invert();
  88188. }
  88189. }
  88190. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  88191. this.upAxisSpace = BABYLON.Space.LOCAL;
  88192. }
  88193. }
  88194. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  88195. /**
  88196. * Gets or sets the minimum yaw angle that the bone can look to
  88197. */
  88198. get: function () {
  88199. return this._minYaw;
  88200. },
  88201. set: function (value) {
  88202. this._minYaw = value;
  88203. this._minYawSin = Math.sin(value);
  88204. this._minYawCos = Math.cos(value);
  88205. if (this._maxYaw != null) {
  88206. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88207. this._yawRange = this._maxYaw - this._minYaw;
  88208. }
  88209. },
  88210. enumerable: true,
  88211. configurable: true
  88212. });
  88213. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  88214. /**
  88215. * Gets or sets the maximum yaw angle that the bone can look to
  88216. */
  88217. get: function () {
  88218. return this._maxYaw;
  88219. },
  88220. set: function (value) {
  88221. this._maxYaw = value;
  88222. this._maxYawSin = Math.sin(value);
  88223. this._maxYawCos = Math.cos(value);
  88224. if (this._minYaw != null) {
  88225. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88226. this._yawRange = this._maxYaw - this._minYaw;
  88227. }
  88228. },
  88229. enumerable: true,
  88230. configurable: true
  88231. });
  88232. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  88233. /**
  88234. * Gets or sets the minimum pitch angle that the bone can look to
  88235. */
  88236. get: function () {
  88237. return this._minPitch;
  88238. },
  88239. set: function (value) {
  88240. this._minPitch = value;
  88241. this._minPitchTan = Math.tan(value);
  88242. },
  88243. enumerable: true,
  88244. configurable: true
  88245. });
  88246. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  88247. /**
  88248. * Gets or sets the maximum pitch angle that the bone can look to
  88249. */
  88250. get: function () {
  88251. return this._maxPitch;
  88252. },
  88253. set: function (value) {
  88254. this._maxPitch = value;
  88255. this._maxPitchTan = Math.tan(value);
  88256. },
  88257. enumerable: true,
  88258. configurable: true
  88259. });
  88260. /**
  88261. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  88262. */
  88263. BoneLookController.prototype.update = function () {
  88264. //skip the first frame when slerping so that the mesh rotation is correct
  88265. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  88266. this._firstFrameSkipped = true;
  88267. return;
  88268. }
  88269. var bone = this.bone;
  88270. var bonePos = BoneLookController._tmpVecs[0];
  88271. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  88272. var target = this.target;
  88273. var _tmpMat1 = BoneLookController._tmpMats[0];
  88274. var _tmpMat2 = BoneLookController._tmpMats[1];
  88275. var mesh = this.mesh;
  88276. var parentBone = bone.getParent();
  88277. var upAxis = BoneLookController._tmpVecs[1];
  88278. upAxis.copyFrom(this.upAxis);
  88279. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  88280. if (this._transformYawPitch) {
  88281. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  88282. }
  88283. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  88284. }
  88285. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  88286. mesh.getDirectionToRef(upAxis, upAxis);
  88287. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  88288. upAxis.normalize();
  88289. }
  88290. }
  88291. var checkYaw = false;
  88292. var checkPitch = false;
  88293. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  88294. checkYaw = true;
  88295. }
  88296. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  88297. checkPitch = true;
  88298. }
  88299. if (checkYaw || checkPitch) {
  88300. var spaceMat = BoneLookController._tmpMats[2];
  88301. var spaceMatInv = BoneLookController._tmpMats[3];
  88302. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  88303. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  88304. }
  88305. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  88306. spaceMat.copyFrom(mesh.getWorldMatrix());
  88307. }
  88308. else {
  88309. var forwardAxis = BoneLookController._tmpVecs[2];
  88310. forwardAxis.copyFrom(this._fowardAxis);
  88311. if (this._transformYawPitch) {
  88312. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  88313. }
  88314. if (parentBone) {
  88315. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  88316. }
  88317. else {
  88318. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  88319. }
  88320. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  88321. rightAxis.normalize();
  88322. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  88323. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  88324. }
  88325. spaceMat.invertToRef(spaceMatInv);
  88326. var xzlen = null;
  88327. if (checkPitch) {
  88328. var localTarget = BoneLookController._tmpVecs[3];
  88329. target.subtractToRef(bonePos, localTarget);
  88330. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88331. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88332. var pitch = Math.atan2(localTarget.y, xzlen);
  88333. var newPitch = pitch;
  88334. if (pitch > this._maxPitch) {
  88335. localTarget.y = this._maxPitchTan * xzlen;
  88336. newPitch = this._maxPitch;
  88337. }
  88338. else if (pitch < this._minPitch) {
  88339. localTarget.y = this._minPitchTan * xzlen;
  88340. newPitch = this._minPitch;
  88341. }
  88342. if (pitch != newPitch) {
  88343. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88344. localTarget.addInPlace(bonePos);
  88345. target = localTarget;
  88346. }
  88347. }
  88348. if (checkYaw) {
  88349. var localTarget = BoneLookController._tmpVecs[4];
  88350. target.subtractToRef(bonePos, localTarget);
  88351. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88352. var yaw = Math.atan2(localTarget.x, localTarget.z);
  88353. var newYaw = yaw;
  88354. if (yaw > this._maxYaw || yaw < this._minYaw) {
  88355. if (xzlen == null) {
  88356. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88357. }
  88358. if (this._yawRange > Math.PI) {
  88359. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  88360. localTarget.z = this._maxYawCos * xzlen;
  88361. localTarget.x = this._maxYawSin * xzlen;
  88362. newYaw = this._maxYaw;
  88363. }
  88364. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  88365. localTarget.z = this._minYawCos * xzlen;
  88366. localTarget.x = this._minYawSin * xzlen;
  88367. newYaw = this._minYaw;
  88368. }
  88369. }
  88370. else {
  88371. if (yaw > this._maxYaw) {
  88372. localTarget.z = this._maxYawCos * xzlen;
  88373. localTarget.x = this._maxYawSin * xzlen;
  88374. newYaw = this._maxYaw;
  88375. }
  88376. else if (yaw < this._minYaw) {
  88377. localTarget.z = this._minYawCos * xzlen;
  88378. localTarget.x = this._minYawSin * xzlen;
  88379. newYaw = this._minYaw;
  88380. }
  88381. }
  88382. }
  88383. if (this._slerping && this._yawRange > Math.PI) {
  88384. //are we going to be crossing into the min/max region?
  88385. var boneFwd = BoneLookController._tmpVecs[8];
  88386. boneFwd.copyFrom(BABYLON.Axis.Z);
  88387. if (this._transformYawPitch) {
  88388. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  88389. }
  88390. var boneRotMat = BoneLookController._tmpMats[4];
  88391. this._boneQuat.toRotationMatrix(boneRotMat);
  88392. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  88393. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  88394. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  88395. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  88396. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  88397. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  88398. if (angBtwTar > angBtwMidYaw) {
  88399. if (xzlen == null) {
  88400. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88401. }
  88402. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  88403. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  88404. if (angBtwMin < angBtwMax) {
  88405. newYaw = boneYaw + Math.PI * .75;
  88406. localTarget.z = Math.cos(newYaw) * xzlen;
  88407. localTarget.x = Math.sin(newYaw) * xzlen;
  88408. }
  88409. else {
  88410. newYaw = boneYaw - Math.PI * .75;
  88411. localTarget.z = Math.cos(newYaw) * xzlen;
  88412. localTarget.x = Math.sin(newYaw) * xzlen;
  88413. }
  88414. }
  88415. }
  88416. if (yaw != newYaw) {
  88417. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88418. localTarget.addInPlace(bonePos);
  88419. target = localTarget;
  88420. }
  88421. }
  88422. }
  88423. var zaxis = BoneLookController._tmpVecs[5];
  88424. var xaxis = BoneLookController._tmpVecs[6];
  88425. var yaxis = BoneLookController._tmpVecs[7];
  88426. var _tmpQuat = BoneLookController._tmpQuat;
  88427. target.subtractToRef(bonePos, zaxis);
  88428. zaxis.normalize();
  88429. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  88430. xaxis.normalize();
  88431. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  88432. yaxis.normalize();
  88433. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  88434. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  88435. return;
  88436. }
  88437. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  88438. return;
  88439. }
  88440. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  88441. return;
  88442. }
  88443. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  88444. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  88445. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  88446. }
  88447. if (this.slerpAmount < 1) {
  88448. if (!this._slerping) {
  88449. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  88450. }
  88451. if (this._transformYawPitch) {
  88452. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88453. }
  88454. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  88455. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  88456. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  88457. this._slerping = true;
  88458. }
  88459. else {
  88460. if (this._transformYawPitch) {
  88461. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88462. }
  88463. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  88464. this._slerping = false;
  88465. }
  88466. };
  88467. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  88468. var angDiff = ang2 - ang1;
  88469. angDiff %= Math.PI * 2;
  88470. if (angDiff > Math.PI) {
  88471. angDiff -= Math.PI * 2;
  88472. }
  88473. else if (angDiff < -Math.PI) {
  88474. angDiff += Math.PI * 2;
  88475. }
  88476. return angDiff;
  88477. };
  88478. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  88479. ang1 %= (2 * Math.PI);
  88480. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88481. ang2 %= (2 * Math.PI);
  88482. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88483. var ab = 0;
  88484. if (ang1 < ang2) {
  88485. ab = ang2 - ang1;
  88486. }
  88487. else {
  88488. ab = ang1 - ang2;
  88489. }
  88490. if (ab > Math.PI) {
  88491. ab = Math.PI * 2 - ab;
  88492. }
  88493. return ab;
  88494. };
  88495. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  88496. ang %= (2 * Math.PI);
  88497. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  88498. ang1 %= (2 * Math.PI);
  88499. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88500. ang2 %= (2 * Math.PI);
  88501. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88502. if (ang1 < ang2) {
  88503. if (ang > ang1 && ang < ang2) {
  88504. return true;
  88505. }
  88506. }
  88507. else {
  88508. if (ang > ang2 && ang < ang1) {
  88509. return true;
  88510. }
  88511. }
  88512. return false;
  88513. };
  88514. 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()];
  88515. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88516. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88517. return BoneLookController;
  88518. }());
  88519. BABYLON.BoneLookController = BoneLookController;
  88520. })(BABYLON || (BABYLON = {}));
  88521. //# sourceMappingURL=babylon.boneLookController.js.map
  88522. var BABYLON;
  88523. (function (BABYLON) {
  88524. /**
  88525. * Class used to handle skinning animations
  88526. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88527. */
  88528. var Skeleton = /** @class */ (function () {
  88529. /**
  88530. * Creates a new skeleton
  88531. * @param name defines the skeleton name
  88532. * @param id defines the skeleton Id
  88533. * @param scene defines the hosting scene
  88534. */
  88535. function Skeleton(
  88536. /** defines the skeleton name */
  88537. name,
  88538. /** defines the skeleton Id */
  88539. id, scene) {
  88540. this.name = name;
  88541. this.id = id;
  88542. /**
  88543. * Gets the list of child bones
  88544. */
  88545. this.bones = new Array();
  88546. /**
  88547. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88548. */
  88549. this.needInitialSkinMatrix = false;
  88550. this._isDirty = true;
  88551. this._meshesWithPoseMatrix = new Array();
  88552. this._identity = BABYLON.Matrix.Identity();
  88553. this._ranges = {};
  88554. this._lastAbsoluteTransformsUpdateId = -1;
  88555. /**
  88556. * Specifies if the skeleton should be serialized
  88557. */
  88558. this.doNotSerialize = false;
  88559. this._animationPropertiesOverride = null;
  88560. // Events
  88561. /**
  88562. * An observable triggered before computing the skeleton's matrices
  88563. */
  88564. this.onBeforeComputeObservable = new BABYLON.Observable();
  88565. this.bones = [];
  88566. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88567. scene.skeletons.push(this);
  88568. //make sure it will recalculate the matrix next time prepare is called.
  88569. this._isDirty = true;
  88570. }
  88571. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88572. /**
  88573. * Gets or sets the animation properties override
  88574. */
  88575. get: function () {
  88576. if (!this._animationPropertiesOverride) {
  88577. return this._scene.animationPropertiesOverride;
  88578. }
  88579. return this._animationPropertiesOverride;
  88580. },
  88581. set: function (value) {
  88582. this._animationPropertiesOverride = value;
  88583. },
  88584. enumerable: true,
  88585. configurable: true
  88586. });
  88587. // Members
  88588. /**
  88589. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88590. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88591. * @returns a Float32Array containing matrices data
  88592. */
  88593. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88594. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88595. return mesh._bonesTransformMatrices;
  88596. }
  88597. if (!this._transformMatrices) {
  88598. this.prepare();
  88599. }
  88600. return this._transformMatrices;
  88601. };
  88602. /**
  88603. * Gets the current hosting scene
  88604. * @returns a scene object
  88605. */
  88606. Skeleton.prototype.getScene = function () {
  88607. return this._scene;
  88608. };
  88609. // Methods
  88610. /**
  88611. * Gets a string representing the current skeleton data
  88612. * @param fullDetails defines a boolean indicating if we want a verbose version
  88613. * @returns a string representing the current skeleton data
  88614. */
  88615. Skeleton.prototype.toString = function (fullDetails) {
  88616. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88617. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88618. if (fullDetails) {
  88619. ret += ", Ranges: {";
  88620. var first = true;
  88621. for (var name_1 in this._ranges) {
  88622. if (first) {
  88623. ret += ", ";
  88624. first = false;
  88625. }
  88626. ret += name_1;
  88627. }
  88628. ret += "}";
  88629. }
  88630. return ret;
  88631. };
  88632. /**
  88633. * Get bone's index searching by name
  88634. * @param name defines bone's name to search for
  88635. * @return the indice of the bone. Returns -1 if not found
  88636. */
  88637. Skeleton.prototype.getBoneIndexByName = function (name) {
  88638. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  88639. if (this.bones[boneIndex].name === name) {
  88640. return boneIndex;
  88641. }
  88642. }
  88643. return -1;
  88644. };
  88645. /**
  88646. * Creater a new animation range
  88647. * @param name defines the name of the range
  88648. * @param from defines the start key
  88649. * @param to defines the end key
  88650. */
  88651. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  88652. // check name not already in use
  88653. if (!this._ranges[name]) {
  88654. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  88655. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88656. if (this.bones[i].animations[0]) {
  88657. this.bones[i].animations[0].createRange(name, from, to);
  88658. }
  88659. }
  88660. }
  88661. };
  88662. /**
  88663. * Delete a specific animation range
  88664. * @param name defines the name of the range
  88665. * @param deleteFrames defines if frames must be removed as well
  88666. */
  88667. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  88668. if (deleteFrames === void 0) { deleteFrames = true; }
  88669. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88670. if (this.bones[i].animations[0]) {
  88671. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  88672. }
  88673. }
  88674. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  88675. };
  88676. /**
  88677. * Gets a specific animation range
  88678. * @param name defines the name of the range to look for
  88679. * @returns the requested animation range or null if not found
  88680. */
  88681. Skeleton.prototype.getAnimationRange = function (name) {
  88682. return this._ranges[name];
  88683. };
  88684. /**
  88685. * Gets the list of all animation ranges defined on this skeleton
  88686. * @returns an array
  88687. */
  88688. Skeleton.prototype.getAnimationRanges = function () {
  88689. var animationRanges = [];
  88690. var name;
  88691. var i = 0;
  88692. for (name in this._ranges) {
  88693. animationRanges[i] = this._ranges[name];
  88694. i++;
  88695. }
  88696. return animationRanges;
  88697. };
  88698. /**
  88699. * Copy animation range from a source skeleton.
  88700. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  88701. * @param source defines the source skeleton
  88702. * @param name defines the name of the range to copy
  88703. * @param rescaleAsRequired defines if rescaling must be applied if required
  88704. * @returns true if operation was successful
  88705. */
  88706. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  88707. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88708. if (this._ranges[name] || !source.getAnimationRange(name)) {
  88709. return false;
  88710. }
  88711. var ret = true;
  88712. var frameOffset = this._getHighestAnimationFrame() + 1;
  88713. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  88714. var boneDict = {};
  88715. var sourceBones = source.bones;
  88716. var nBones;
  88717. var i;
  88718. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  88719. boneDict[sourceBones[i].name] = sourceBones[i];
  88720. }
  88721. if (this.bones.length !== sourceBones.length) {
  88722. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  88723. ret = false;
  88724. }
  88725. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  88726. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  88727. var boneName = this.bones[i].name;
  88728. var sourceBone = boneDict[boneName];
  88729. if (sourceBone) {
  88730. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  88731. }
  88732. else {
  88733. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  88734. ret = false;
  88735. }
  88736. }
  88737. // do not call createAnimationRange(), since it also is done to bones, which was already done
  88738. var range = source.getAnimationRange(name);
  88739. if (range) {
  88740. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  88741. }
  88742. return ret;
  88743. };
  88744. /**
  88745. * Forces the skeleton to go to rest pose
  88746. */
  88747. Skeleton.prototype.returnToRest = function () {
  88748. for (var index = 0; index < this.bones.length; index++) {
  88749. this.bones[index].returnToRest();
  88750. }
  88751. };
  88752. Skeleton.prototype._getHighestAnimationFrame = function () {
  88753. var ret = 0;
  88754. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88755. if (this.bones[i].animations[0]) {
  88756. var highest = this.bones[i].animations[0].getHighestFrame();
  88757. if (ret < highest) {
  88758. ret = highest;
  88759. }
  88760. }
  88761. }
  88762. return ret;
  88763. };
  88764. /**
  88765. * Begin a specific animation range
  88766. * @param name defines the name of the range to start
  88767. * @param loop defines if looping must be turned on (false by default)
  88768. * @param speedRatio defines the speed ratio to apply (1 by default)
  88769. * @param onAnimationEnd defines a callback which will be called when animation will end
  88770. * @returns a new animatable
  88771. */
  88772. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  88773. var range = this.getAnimationRange(name);
  88774. if (!range) {
  88775. return null;
  88776. }
  88777. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  88778. };
  88779. /** @hidden */
  88780. Skeleton.prototype._markAsDirty = function () {
  88781. this._isDirty = true;
  88782. };
  88783. /** @hidden */
  88784. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  88785. this._meshesWithPoseMatrix.push(mesh);
  88786. };
  88787. /** @hidden */
  88788. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  88789. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  88790. if (index > -1) {
  88791. this._meshesWithPoseMatrix.splice(index, 1);
  88792. }
  88793. };
  88794. /** @hidden */
  88795. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  88796. this.onBeforeComputeObservable.notifyObservers(this);
  88797. for (var index = 0; index < this.bones.length; index++) {
  88798. var bone = this.bones[index];
  88799. var parentBone = bone.getParent();
  88800. if (parentBone) {
  88801. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  88802. }
  88803. else {
  88804. if (initialSkinMatrix) {
  88805. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  88806. }
  88807. else {
  88808. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  88809. }
  88810. }
  88811. if (bone._index !== -1) {
  88812. var mappedIndex = bone._index === null ? index : bone._index;
  88813. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  88814. }
  88815. }
  88816. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  88817. };
  88818. /**
  88819. * Build all resources required to render a skeleton
  88820. */
  88821. Skeleton.prototype.prepare = function () {
  88822. if (!this._isDirty) {
  88823. return;
  88824. }
  88825. if (this.needInitialSkinMatrix) {
  88826. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  88827. var mesh = this._meshesWithPoseMatrix[index];
  88828. var poseMatrix = mesh.getPoseMatrix();
  88829. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  88830. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88831. }
  88832. if (this._synchronizedWithMesh !== mesh) {
  88833. this._synchronizedWithMesh = mesh;
  88834. // Prepare bones
  88835. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  88836. var bone = this.bones[boneIndex];
  88837. if (!bone.getParent()) {
  88838. var matrix = bone.getBaseMatrix();
  88839. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  88840. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  88841. }
  88842. }
  88843. }
  88844. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  88845. }
  88846. }
  88847. else {
  88848. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  88849. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88850. }
  88851. this._computeTransformMatrices(this._transformMatrices, null);
  88852. }
  88853. this._isDirty = false;
  88854. this._scene._activeBones.addCount(this.bones.length, false);
  88855. };
  88856. /**
  88857. * Gets the list of animatables currently running for this skeleton
  88858. * @returns an array of animatables
  88859. */
  88860. Skeleton.prototype.getAnimatables = function () {
  88861. if (!this._animatables || this._animatables.length !== this.bones.length) {
  88862. this._animatables = [];
  88863. for (var index = 0; index < this.bones.length; index++) {
  88864. this._animatables.push(this.bones[index]);
  88865. }
  88866. }
  88867. return this._animatables;
  88868. };
  88869. /**
  88870. * Clone the current skeleton
  88871. * @param name defines the name of the new skeleton
  88872. * @param id defines the id of the enw skeleton
  88873. * @returns the new skeleton
  88874. */
  88875. Skeleton.prototype.clone = function (name, id) {
  88876. var result = new Skeleton(name, id || name, this._scene);
  88877. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88878. for (var index = 0; index < this.bones.length; index++) {
  88879. var source = this.bones[index];
  88880. var parentBone = null;
  88881. var parent_1 = source.getParent();
  88882. if (parent_1) {
  88883. var parentIndex = this.bones.indexOf(parent_1);
  88884. parentBone = result.bones[parentIndex];
  88885. }
  88886. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88887. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88888. }
  88889. if (this._ranges) {
  88890. result._ranges = {};
  88891. for (var rangeName in this._ranges) {
  88892. var range = this._ranges[rangeName];
  88893. if (range) {
  88894. result._ranges[rangeName] = range.clone();
  88895. }
  88896. }
  88897. }
  88898. this._isDirty = true;
  88899. return result;
  88900. };
  88901. /**
  88902. * Enable animation blending for this skeleton
  88903. * @param blendingSpeed defines the blending speed to apply
  88904. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88905. */
  88906. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88907. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88908. this.bones.forEach(function (bone) {
  88909. bone.animations.forEach(function (animation) {
  88910. animation.enableBlending = true;
  88911. animation.blendingSpeed = blendingSpeed;
  88912. });
  88913. });
  88914. };
  88915. /**
  88916. * Releases all resources associated with the current skeleton
  88917. */
  88918. Skeleton.prototype.dispose = function () {
  88919. this._meshesWithPoseMatrix = [];
  88920. // Animations
  88921. this.getScene().stopAnimation(this);
  88922. // Remove from scene
  88923. this.getScene().removeSkeleton(this);
  88924. };
  88925. /**
  88926. * Serialize the skeleton in a JSON object
  88927. * @returns a JSON object
  88928. */
  88929. Skeleton.prototype.serialize = function () {
  88930. var serializationObject = {};
  88931. serializationObject.name = this.name;
  88932. serializationObject.id = this.id;
  88933. if (this.dimensionsAtRest) {
  88934. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88935. }
  88936. serializationObject.bones = [];
  88937. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88938. for (var index = 0; index < this.bones.length; index++) {
  88939. var bone = this.bones[index];
  88940. var parent_2 = bone.getParent();
  88941. var serializedBone = {
  88942. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88943. name: bone.name,
  88944. matrix: bone.getBaseMatrix().toArray(),
  88945. rest: bone.getRestPose().toArray()
  88946. };
  88947. serializationObject.bones.push(serializedBone);
  88948. if (bone.length) {
  88949. serializedBone.length = bone.length;
  88950. }
  88951. if (bone.metadata) {
  88952. serializedBone.metadata = bone.metadata;
  88953. }
  88954. if (bone.animations && bone.animations.length > 0) {
  88955. serializedBone.animation = bone.animations[0].serialize();
  88956. }
  88957. serializationObject.ranges = [];
  88958. for (var name in this._ranges) {
  88959. var source = this._ranges[name];
  88960. if (!source) {
  88961. continue;
  88962. }
  88963. var range = {};
  88964. range.name = name;
  88965. range.from = source.from;
  88966. range.to = source.to;
  88967. serializationObject.ranges.push(range);
  88968. }
  88969. }
  88970. return serializationObject;
  88971. };
  88972. /**
  88973. * Creates a new skeleton from serialized data
  88974. * @param parsedSkeleton defines the serialized data
  88975. * @param scene defines the hosting scene
  88976. * @returns a new skeleton
  88977. */
  88978. Skeleton.Parse = function (parsedSkeleton, scene) {
  88979. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  88980. if (parsedSkeleton.dimensionsAtRest) {
  88981. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  88982. }
  88983. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  88984. var index;
  88985. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  88986. var parsedBone = parsedSkeleton.bones[index];
  88987. var parentBone = null;
  88988. if (parsedBone.parentBoneIndex > -1) {
  88989. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  88990. }
  88991. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  88992. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  88993. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  88994. bone.id = parsedBone.id;
  88995. }
  88996. if (parsedBone.length) {
  88997. bone.length = parsedBone.length;
  88998. }
  88999. if (parsedBone.metadata) {
  89000. bone.metadata = parsedBone.metadata;
  89001. }
  89002. if (parsedBone.animation) {
  89003. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  89004. }
  89005. }
  89006. // placed after bones, so createAnimationRange can cascade down
  89007. if (parsedSkeleton.ranges) {
  89008. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  89009. var data = parsedSkeleton.ranges[index];
  89010. skeleton.createAnimationRange(data.name, data.from, data.to);
  89011. }
  89012. }
  89013. return skeleton;
  89014. };
  89015. /**
  89016. * Compute all node absolute transforms
  89017. * @param forceUpdate defines if computation must be done even if cache is up to date
  89018. */
  89019. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  89020. if (forceUpdate === void 0) { forceUpdate = false; }
  89021. var renderId = this._scene.getRenderId();
  89022. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  89023. this.bones[0].computeAbsoluteTransforms();
  89024. this._lastAbsoluteTransformsUpdateId = renderId;
  89025. }
  89026. };
  89027. /**
  89028. * Gets the root pose matrix
  89029. * @returns a matrix
  89030. */
  89031. Skeleton.prototype.getPoseMatrix = function () {
  89032. var poseMatrix = null;
  89033. if (this._meshesWithPoseMatrix.length > 0) {
  89034. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  89035. }
  89036. return poseMatrix;
  89037. };
  89038. /**
  89039. * Sorts bones per internal index
  89040. */
  89041. Skeleton.prototype.sortBones = function () {
  89042. var bones = new Array();
  89043. var visited = new Array(this.bones.length);
  89044. for (var index = 0; index < this.bones.length; index++) {
  89045. this._sortBones(index, bones, visited);
  89046. }
  89047. this.bones = bones;
  89048. };
  89049. Skeleton.prototype._sortBones = function (index, bones, visited) {
  89050. if (visited[index]) {
  89051. return;
  89052. }
  89053. visited[index] = true;
  89054. var bone = this.bones[index];
  89055. if (bone._index === undefined) {
  89056. bone._index = index;
  89057. }
  89058. var parentBone = bone.getParent();
  89059. if (parentBone) {
  89060. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  89061. }
  89062. bones.push(bone);
  89063. };
  89064. return Skeleton;
  89065. }());
  89066. BABYLON.Skeleton = Skeleton;
  89067. })(BABYLON || (BABYLON = {}));
  89068. //# sourceMappingURL=babylon.skeleton.js.map
  89069. var BABYLON;
  89070. (function (BABYLON) {
  89071. ;
  89072. /**
  89073. * This groups tools to convert HDR texture to native colors array.
  89074. */
  89075. var HDRTools = /** @class */ (function () {
  89076. function HDRTools() {
  89077. }
  89078. HDRTools.Ldexp = function (mantissa, exponent) {
  89079. if (exponent > 1023) {
  89080. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  89081. }
  89082. if (exponent < -1074) {
  89083. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  89084. }
  89085. return mantissa * Math.pow(2, exponent);
  89086. };
  89087. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  89088. if (exponent > 0) { /*nonzero pixel*/
  89089. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  89090. float32array[index + 0] = red * exponent;
  89091. float32array[index + 1] = green * exponent;
  89092. float32array[index + 2] = blue * exponent;
  89093. }
  89094. else {
  89095. float32array[index + 0] = 0;
  89096. float32array[index + 1] = 0;
  89097. float32array[index + 2] = 0;
  89098. }
  89099. };
  89100. HDRTools.readStringLine = function (uint8array, startIndex) {
  89101. var line = "";
  89102. var character = "";
  89103. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  89104. character = String.fromCharCode(uint8array[i]);
  89105. if (character == "\n") {
  89106. break;
  89107. }
  89108. line += character;
  89109. }
  89110. return line;
  89111. };
  89112. /**
  89113. * Reads header information from an RGBE texture stored in a native array.
  89114. * More information on this format are available here:
  89115. * https://en.wikipedia.org/wiki/RGBE_image_format
  89116. *
  89117. * @param uint8array The binary file stored in native array.
  89118. * @return The header information.
  89119. */
  89120. HDRTools.RGBE_ReadHeader = function (uint8array) {
  89121. var height = 0;
  89122. var width = 0;
  89123. var line = this.readStringLine(uint8array, 0);
  89124. if (line[0] != '#' || line[1] != '?') {
  89125. throw "Bad HDR Format.";
  89126. }
  89127. var endOfHeader = false;
  89128. var findFormat = false;
  89129. var lineIndex = 0;
  89130. do {
  89131. lineIndex += (line.length + 1);
  89132. line = this.readStringLine(uint8array, lineIndex);
  89133. if (line == "FORMAT=32-bit_rle_rgbe") {
  89134. findFormat = true;
  89135. }
  89136. else if (line.length == 0) {
  89137. endOfHeader = true;
  89138. }
  89139. } while (!endOfHeader);
  89140. if (!findFormat) {
  89141. throw "HDR Bad header format, unsupported FORMAT";
  89142. }
  89143. lineIndex += (line.length + 1);
  89144. line = this.readStringLine(uint8array, lineIndex);
  89145. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  89146. var match = sizeRegexp.exec(line);
  89147. // TODO. Support +Y and -X if needed.
  89148. if (!match || match.length < 3) {
  89149. throw "HDR Bad header format, no size";
  89150. }
  89151. width = parseInt(match[2]);
  89152. height = parseInt(match[1]);
  89153. if (width < 8 || width > 0x7fff) {
  89154. throw "HDR Bad header format, unsupported size";
  89155. }
  89156. lineIndex += (line.length + 1);
  89157. return {
  89158. height: height,
  89159. width: width,
  89160. dataPosition: lineIndex
  89161. };
  89162. };
  89163. /**
  89164. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  89165. * This RGBE texture needs to store the information as a panorama.
  89166. *
  89167. * More information on this format are available here:
  89168. * https://en.wikipedia.org/wiki/RGBE_image_format
  89169. *
  89170. * @param buffer The binary file stored in an array buffer.
  89171. * @param size The expected size of the extracted cubemap.
  89172. * @return The Cube Map information.
  89173. */
  89174. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  89175. var uint8array = new Uint8Array(buffer);
  89176. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  89177. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89178. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  89179. return cubeMapData;
  89180. };
  89181. /**
  89182. * Returns the pixels data extracted from an RGBE texture.
  89183. * This pixels will be stored left to right up to down in the R G B order in one array.
  89184. *
  89185. * More information on this format are available here:
  89186. * https://en.wikipedia.org/wiki/RGBE_image_format
  89187. *
  89188. * @param uint8array The binary file stored in an array buffer.
  89189. * @param hdrInfo The header information of the file.
  89190. * @return The pixels data in RGB right to left up to down order.
  89191. */
  89192. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  89193. // Keep for multi format supports.
  89194. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89195. };
  89196. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  89197. var num_scanlines = hdrInfo.height;
  89198. var scanline_width = hdrInfo.width;
  89199. var a, b, c, d, count;
  89200. var dataIndex = hdrInfo.dataPosition;
  89201. var index = 0, endIndex = 0, i = 0;
  89202. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  89203. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  89204. // 3 channels of 4 bytes per pixel in float.
  89205. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  89206. var resultArray = new Float32Array(resultBuffer);
  89207. // read in each successive scanline
  89208. while (num_scanlines > 0) {
  89209. a = uint8array[dataIndex++];
  89210. b = uint8array[dataIndex++];
  89211. c = uint8array[dataIndex++];
  89212. d = uint8array[dataIndex++];
  89213. if (a != 2 || b != 2 || (c & 0x80)) {
  89214. // this file is not run length encoded
  89215. throw "HDR Bad header format, not RLE";
  89216. }
  89217. if (((c << 8) | d) != scanline_width) {
  89218. throw "HDR Bad header format, wrong scan line width";
  89219. }
  89220. index = 0;
  89221. // read each of the four channels for the scanline into the buffer
  89222. for (i = 0; i < 4; i++) {
  89223. endIndex = (i + 1) * scanline_width;
  89224. while (index < endIndex) {
  89225. a = uint8array[dataIndex++];
  89226. b = uint8array[dataIndex++];
  89227. if (a > 128) {
  89228. // a run of the same value
  89229. count = a - 128;
  89230. if ((count == 0) || (count > endIndex - index)) {
  89231. throw "HDR Bad Format, bad scanline data (run)";
  89232. }
  89233. while (count-- > 0) {
  89234. scanLineArray[index++] = b;
  89235. }
  89236. }
  89237. else {
  89238. // a non-run
  89239. count = a;
  89240. if ((count == 0) || (count > endIndex - index)) {
  89241. throw "HDR Bad Format, bad scanline data (non-run)";
  89242. }
  89243. scanLineArray[index++] = b;
  89244. if (--count > 0) {
  89245. for (var j = 0; j < count; j++) {
  89246. scanLineArray[index++] = uint8array[dataIndex++];
  89247. }
  89248. }
  89249. }
  89250. }
  89251. }
  89252. // now convert data from buffer into floats
  89253. for (i = 0; i < scanline_width; i++) {
  89254. a = scanLineArray[i];
  89255. b = scanLineArray[i + scanline_width];
  89256. c = scanLineArray[i + 2 * scanline_width];
  89257. d = scanLineArray[i + 3 * scanline_width];
  89258. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  89259. }
  89260. num_scanlines--;
  89261. }
  89262. return resultArray;
  89263. };
  89264. return HDRTools;
  89265. }());
  89266. BABYLON.HDRTools = HDRTools;
  89267. })(BABYLON || (BABYLON = {}));
  89268. //# sourceMappingURL=babylon.hdr.js.map
  89269. var BABYLON;
  89270. (function (BABYLON) {
  89271. /**
  89272. * This represents a texture coming from an HDR input.
  89273. *
  89274. * The only supported format is currently panorama picture stored in RGBE format.
  89275. * Example of such files can be found on HDRLib: http://hdrlib.com/
  89276. */
  89277. var HDRCubeTexture = /** @class */ (function (_super) {
  89278. __extends(HDRCubeTexture, _super);
  89279. /**
  89280. * Instantiates an HDRTexture from the following parameters.
  89281. *
  89282. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  89283. * @param scene The scene the texture will be used in
  89284. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  89285. * @param noMipmap Forces to not generate the mipmap if true
  89286. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  89287. * @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)
  89288. * @param reserved Reserved flag for internal use.
  89289. */
  89290. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  89291. if (noMipmap === void 0) { noMipmap = false; }
  89292. if (generateHarmonics === void 0) { generateHarmonics = true; }
  89293. if (gammaSpace === void 0) { gammaSpace = false; }
  89294. if (reserved === void 0) { reserved = false; }
  89295. if (onLoad === void 0) { onLoad = null; }
  89296. if (onError === void 0) { onError = null; }
  89297. var _this = _super.call(this, scene) || this;
  89298. _this._generateHarmonics = true;
  89299. _this._onLoad = null;
  89300. _this._onError = null;
  89301. /**
  89302. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  89303. */
  89304. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  89305. _this._isBlocking = true;
  89306. _this._rotationY = 0;
  89307. /**
  89308. * Gets or sets the center of the bounding box associated with the cube texture
  89309. * It must define where the camera used to render the texture was set
  89310. */
  89311. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  89312. if (!url) {
  89313. return _this;
  89314. }
  89315. _this.name = url;
  89316. _this.url = url;
  89317. _this.hasAlpha = false;
  89318. _this.isCube = true;
  89319. _this._textureMatrix = BABYLON.Matrix.Identity();
  89320. _this._onLoad = onLoad;
  89321. _this._onError = onError;
  89322. _this.gammaSpace = gammaSpace;
  89323. _this._noMipmap = noMipmap;
  89324. _this._size = size;
  89325. _this._texture = _this._getFromCache(url, _this._noMipmap);
  89326. if (!_this._texture) {
  89327. if (!scene.useDelayedTextureLoading) {
  89328. _this.loadTexture();
  89329. }
  89330. else {
  89331. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89332. }
  89333. }
  89334. return _this;
  89335. }
  89336. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  89337. /**
  89338. * Gets wether or not the texture is blocking during loading.
  89339. */
  89340. get: function () {
  89341. return this._isBlocking;
  89342. },
  89343. /**
  89344. * Sets wether or not the texture is blocking during loading.
  89345. */
  89346. set: function (value) {
  89347. this._isBlocking = value;
  89348. },
  89349. enumerable: true,
  89350. configurable: true
  89351. });
  89352. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  89353. /**
  89354. * Gets texture matrix rotation angle around Y axis radians.
  89355. */
  89356. get: function () {
  89357. return this._rotationY;
  89358. },
  89359. /**
  89360. * Sets texture matrix rotation angle around Y axis in radians.
  89361. */
  89362. set: function (value) {
  89363. this._rotationY = value;
  89364. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  89365. },
  89366. enumerable: true,
  89367. configurable: true
  89368. });
  89369. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  89370. get: function () {
  89371. return this._boundingBoxSize;
  89372. },
  89373. /**
  89374. * Gets or sets the size of the bounding box associated with the cube texture
  89375. * When defined, the cubemap will switch to local mode
  89376. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  89377. * @example https://www.babylonjs-playground.com/#RNASML
  89378. */
  89379. set: function (value) {
  89380. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  89381. return;
  89382. }
  89383. this._boundingBoxSize = value;
  89384. var scene = this.getScene();
  89385. if (scene) {
  89386. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  89387. }
  89388. },
  89389. enumerable: true,
  89390. configurable: true
  89391. });
  89392. /**
  89393. * Occurs when the file is raw .hdr file.
  89394. */
  89395. HDRCubeTexture.prototype.loadTexture = function () {
  89396. var _this = this;
  89397. var callback = function (buffer) {
  89398. _this.lodGenerationOffset = 0.0;
  89399. _this.lodGenerationScale = 0.8;
  89400. var scene = _this.getScene();
  89401. if (!scene) {
  89402. return null;
  89403. }
  89404. // Extract the raw linear data.
  89405. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  89406. // Generate harmonics if needed.
  89407. if (_this._generateHarmonics) {
  89408. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  89409. _this.sphericalPolynomial = sphericalPolynomial;
  89410. }
  89411. var results = [];
  89412. var byteArray = null;
  89413. // Push each faces.
  89414. for (var j = 0; j < 6; j++) {
  89415. // Create uintarray fallback.
  89416. if (!scene.getEngine().getCaps().textureFloat) {
  89417. // 3 channels of 1 bytes per pixel in bytes.
  89418. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  89419. byteArray = new Uint8Array(byteBuffer);
  89420. }
  89421. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  89422. // If special cases.
  89423. if (_this.gammaSpace || byteArray) {
  89424. for (var i = 0; i < _this._size * _this._size; i++) {
  89425. // Put in gamma space if requested.
  89426. if (_this.gammaSpace) {
  89427. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  89428. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  89429. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  89430. }
  89431. // Convert to int texture for fallback.
  89432. if (byteArray) {
  89433. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  89434. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  89435. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  89436. // May use luminance instead if the result is not accurate.
  89437. var max = Math.max(Math.max(r, g), b);
  89438. if (max > 255) {
  89439. var scale = 255 / max;
  89440. r *= scale;
  89441. g *= scale;
  89442. b *= scale;
  89443. }
  89444. byteArray[(i * 3) + 0] = r;
  89445. byteArray[(i * 3) + 1] = g;
  89446. byteArray[(i * 3) + 2] = b;
  89447. }
  89448. }
  89449. }
  89450. if (byteArray) {
  89451. results.push(byteArray);
  89452. }
  89453. else {
  89454. results.push(dataFace);
  89455. }
  89456. }
  89457. return results;
  89458. };
  89459. var scene = this.getScene();
  89460. if (scene) {
  89461. 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);
  89462. }
  89463. };
  89464. HDRCubeTexture.prototype.clone = function () {
  89465. var scene = this.getScene();
  89466. if (!scene) {
  89467. return this;
  89468. }
  89469. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  89470. // Base texture
  89471. newTexture.level = this.level;
  89472. newTexture.wrapU = this.wrapU;
  89473. newTexture.wrapV = this.wrapV;
  89474. newTexture.coordinatesIndex = this.coordinatesIndex;
  89475. newTexture.coordinatesMode = this.coordinatesMode;
  89476. return newTexture;
  89477. };
  89478. // Methods
  89479. HDRCubeTexture.prototype.delayLoad = function () {
  89480. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89481. return;
  89482. }
  89483. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89484. this._texture = this._getFromCache(this.url, this._noMipmap);
  89485. if (!this._texture) {
  89486. this.loadTexture();
  89487. }
  89488. };
  89489. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  89490. return this._textureMatrix;
  89491. };
  89492. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  89493. this._textureMatrix = value;
  89494. };
  89495. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89496. var texture = null;
  89497. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89498. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  89499. texture.name = parsedTexture.name;
  89500. texture.hasAlpha = parsedTexture.hasAlpha;
  89501. texture.level = parsedTexture.level;
  89502. texture.coordinatesMode = parsedTexture.coordinatesMode;
  89503. texture.isBlocking = parsedTexture.isBlocking;
  89504. }
  89505. if (texture) {
  89506. if (parsedTexture.boundingBoxPosition) {
  89507. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  89508. }
  89509. if (parsedTexture.boundingBoxSize) {
  89510. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89511. }
  89512. if (parsedTexture.rotationY) {
  89513. texture.rotationY = parsedTexture.rotationY;
  89514. }
  89515. }
  89516. return texture;
  89517. };
  89518. HDRCubeTexture.prototype.serialize = function () {
  89519. if (!this.name) {
  89520. return null;
  89521. }
  89522. var serializationObject = {};
  89523. serializationObject.name = this.name;
  89524. serializationObject.hasAlpha = this.hasAlpha;
  89525. serializationObject.isCube = true;
  89526. serializationObject.level = this.level;
  89527. serializationObject.size = this._size;
  89528. serializationObject.coordinatesMode = this.coordinatesMode;
  89529. serializationObject.useInGammaSpace = this.gammaSpace;
  89530. serializationObject.generateHarmonics = this._generateHarmonics;
  89531. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89532. serializationObject.noMipmap = this._noMipmap;
  89533. serializationObject.isBlocking = this._isBlocking;
  89534. serializationObject.rotationY = this._rotationY;
  89535. return serializationObject;
  89536. };
  89537. HDRCubeTexture._facesMapping = [
  89538. "right",
  89539. "left",
  89540. "up",
  89541. "down",
  89542. "front",
  89543. "back"
  89544. ];
  89545. return HDRCubeTexture;
  89546. }(BABYLON.BaseTexture));
  89547. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89548. })(BABYLON || (BABYLON = {}));
  89549. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89550. var BABYLON;
  89551. (function (BABYLON) {
  89552. /**
  89553. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89554. */
  89555. var PanoramaToCubeMapTools = /** @class */ (function () {
  89556. function PanoramaToCubeMapTools() {
  89557. }
  89558. /**
  89559. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89560. *
  89561. * @param float32Array The source data.
  89562. * @param inputWidth The width of the input panorama.
  89563. * @param inputhHeight The height of the input panorama.
  89564. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89565. * @return The cubemap data
  89566. */
  89567. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89568. if (!float32Array) {
  89569. throw "ConvertPanoramaToCubemap: input cannot be null";
  89570. }
  89571. if (float32Array.length != inputWidth * inputHeight * 3) {
  89572. throw "ConvertPanoramaToCubemap: input size is wrong";
  89573. }
  89574. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89575. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89576. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89577. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89578. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89579. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89580. return {
  89581. front: textureFront,
  89582. back: textureBack,
  89583. left: textureLeft,
  89584. right: textureRight,
  89585. up: textureUp,
  89586. down: textureDown,
  89587. size: size,
  89588. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89589. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89590. gammaSpace: false,
  89591. };
  89592. };
  89593. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89594. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89595. var textureArray = new Float32Array(buffer);
  89596. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89597. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89598. var dy = 1 / texSize;
  89599. var fy = 0;
  89600. for (var y = 0; y < texSize; y++) {
  89601. var xv1 = faceData[0];
  89602. var xv2 = faceData[2];
  89603. for (var x = 0; x < texSize; x++) {
  89604. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89605. v.normalize();
  89606. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89607. // 3 channels per pixels
  89608. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89609. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89610. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89611. xv1 = xv1.add(rotDX1);
  89612. xv2 = xv2.add(rotDX2);
  89613. }
  89614. fy += dy;
  89615. }
  89616. return textureArray;
  89617. };
  89618. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  89619. var theta = Math.atan2(vDir.z, vDir.x);
  89620. var phi = Math.acos(vDir.y);
  89621. while (theta < -Math.PI)
  89622. theta += 2 * Math.PI;
  89623. while (theta > Math.PI)
  89624. theta -= 2 * Math.PI;
  89625. var dx = theta / Math.PI;
  89626. var dy = phi / Math.PI;
  89627. // recenter.
  89628. dx = dx * 0.5 + 0.5;
  89629. var px = Math.round(dx * inputWidth);
  89630. if (px < 0)
  89631. px = 0;
  89632. else if (px >= inputWidth)
  89633. px = inputWidth - 1;
  89634. var py = Math.round(dy * inputHeight);
  89635. if (py < 0)
  89636. py = 0;
  89637. else if (py >= inputHeight)
  89638. py = inputHeight - 1;
  89639. var inputY = (inputHeight - py - 1);
  89640. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  89641. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  89642. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  89643. return {
  89644. r: r,
  89645. g: g,
  89646. b: b
  89647. };
  89648. };
  89649. PanoramaToCubeMapTools.FACE_FRONT = [
  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. new BABYLON.Vector3(1.0, 1.0, -1.0)
  89654. ];
  89655. PanoramaToCubeMapTools.FACE_BACK = [
  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. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  89660. ];
  89661. PanoramaToCubeMapTools.FACE_RIGHT = [
  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. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89666. ];
  89667. PanoramaToCubeMapTools.FACE_LEFT = [
  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. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  89672. ];
  89673. PanoramaToCubeMapTools.FACE_DOWN = [
  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. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89678. ];
  89679. PanoramaToCubeMapTools.FACE_UP = [
  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. new BABYLON.Vector3(1.0, -1.0, -1.0)
  89684. ];
  89685. return PanoramaToCubeMapTools;
  89686. }());
  89687. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  89688. })(BABYLON || (BABYLON = {}));
  89689. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  89690. var BABYLON;
  89691. (function (BABYLON) {
  89692. var IndexedVector2 = /** @class */ (function (_super) {
  89693. __extends(IndexedVector2, _super);
  89694. function IndexedVector2(original, index) {
  89695. var _this = _super.call(this, original.x, original.y) || this;
  89696. _this.index = index;
  89697. return _this;
  89698. }
  89699. return IndexedVector2;
  89700. }(BABYLON.Vector2));
  89701. var PolygonPoints = /** @class */ (function () {
  89702. function PolygonPoints() {
  89703. this.elements = new Array();
  89704. }
  89705. PolygonPoints.prototype.add = function (originalPoints) {
  89706. var _this = this;
  89707. var result = new Array();
  89708. originalPoints.forEach(function (point) {
  89709. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  89710. var newPoint = new IndexedVector2(point, _this.elements.length);
  89711. result.push(newPoint);
  89712. _this.elements.push(newPoint);
  89713. }
  89714. });
  89715. return result;
  89716. };
  89717. PolygonPoints.prototype.computeBounds = function () {
  89718. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89719. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89720. this.elements.forEach(function (point) {
  89721. // x
  89722. if (point.x < lmin.x) {
  89723. lmin.x = point.x;
  89724. }
  89725. else if (point.x > lmax.x) {
  89726. lmax.x = point.x;
  89727. }
  89728. // y
  89729. if (point.y < lmin.y) {
  89730. lmin.y = point.y;
  89731. }
  89732. else if (point.y > lmax.y) {
  89733. lmax.y = point.y;
  89734. }
  89735. });
  89736. return {
  89737. min: lmin,
  89738. max: lmax,
  89739. width: lmax.x - lmin.x,
  89740. height: lmax.y - lmin.y
  89741. };
  89742. };
  89743. return PolygonPoints;
  89744. }());
  89745. var Polygon = /** @class */ (function () {
  89746. function Polygon() {
  89747. }
  89748. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  89749. return [
  89750. new BABYLON.Vector2(xmin, ymin),
  89751. new BABYLON.Vector2(xmax, ymin),
  89752. new BABYLON.Vector2(xmax, ymax),
  89753. new BABYLON.Vector2(xmin, ymax)
  89754. ];
  89755. };
  89756. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  89757. if (cx === void 0) { cx = 0; }
  89758. if (cy === void 0) { cy = 0; }
  89759. if (numberOfSides === void 0) { numberOfSides = 32; }
  89760. var result = new Array();
  89761. var angle = 0;
  89762. var increment = (Math.PI * 2) / numberOfSides;
  89763. for (var i = 0; i < numberOfSides; i++) {
  89764. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  89765. angle -= increment;
  89766. }
  89767. return result;
  89768. };
  89769. Polygon.Parse = function (input) {
  89770. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  89771. var i, result = [];
  89772. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  89773. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  89774. }
  89775. return result;
  89776. };
  89777. Polygon.StartingAt = function (x, y) {
  89778. return BABYLON.Path2.StartingAt(x, y);
  89779. };
  89780. return Polygon;
  89781. }());
  89782. BABYLON.Polygon = Polygon;
  89783. var PolygonMeshBuilder = /** @class */ (function () {
  89784. function PolygonMeshBuilder(name, contours, scene) {
  89785. this._points = new PolygonPoints();
  89786. this._outlinepoints = new PolygonPoints();
  89787. this._holes = new Array();
  89788. this._epoints = new Array();
  89789. this._eholes = new Array();
  89790. this._name = name;
  89791. this._scene = scene;
  89792. var points;
  89793. if (contours instanceof BABYLON.Path2) {
  89794. points = contours.getPoints();
  89795. }
  89796. else {
  89797. points = contours;
  89798. }
  89799. this._addToepoint(points);
  89800. this._points.add(points);
  89801. this._outlinepoints.add(points);
  89802. if (typeof earcut === 'undefined') {
  89803. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  89804. }
  89805. }
  89806. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  89807. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  89808. var p = points_1[_i];
  89809. this._epoints.push(p.x, p.y);
  89810. }
  89811. };
  89812. PolygonMeshBuilder.prototype.addHole = function (hole) {
  89813. this._points.add(hole);
  89814. var holepoints = new PolygonPoints();
  89815. holepoints.add(hole);
  89816. this._holes.push(holepoints);
  89817. this._eholes.push(this._epoints.length / 2);
  89818. this._addToepoint(hole);
  89819. return this;
  89820. };
  89821. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  89822. var _this = this;
  89823. if (updatable === void 0) { updatable = false; }
  89824. if (depth === void 0) { depth = 0; }
  89825. var result = new BABYLON.Mesh(this._name, this._scene);
  89826. var normals = new Array();
  89827. var positions = new Array();
  89828. var uvs = new Array();
  89829. var bounds = this._points.computeBounds();
  89830. this._points.elements.forEach(function (p) {
  89831. normals.push(0, 1.0, 0);
  89832. positions.push(p.x, 0, p.y);
  89833. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  89834. });
  89835. var indices = new Array();
  89836. var res = earcut(this._epoints, this._eholes, 2);
  89837. for (var i = 0; i < res.length; i++) {
  89838. indices.push(res[i]);
  89839. }
  89840. if (depth > 0) {
  89841. var positionscount = (positions.length / 3); //get the current pointcount
  89842. this._points.elements.forEach(function (p) {
  89843. normals.push(0, -1.0, 0);
  89844. positions.push(p.x, -depth, p.y);
  89845. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  89846. });
  89847. var totalCount = indices.length;
  89848. for (var i = 0; i < totalCount; i += 3) {
  89849. var i0 = indices[i + 0];
  89850. var i1 = indices[i + 1];
  89851. var i2 = indices[i + 2];
  89852. indices.push(i2 + positionscount);
  89853. indices.push(i1 + positionscount);
  89854. indices.push(i0 + positionscount);
  89855. }
  89856. //Add the sides
  89857. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  89858. this._holes.forEach(function (hole) {
  89859. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  89860. });
  89861. }
  89862. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  89863. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  89864. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  89865. result.setIndices(indices);
  89866. return result;
  89867. };
  89868. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  89869. var StartIndex = positions.length / 3;
  89870. var ulength = 0;
  89871. for (var i = 0; i < points.elements.length; i++) {
  89872. var p = points.elements[i];
  89873. var p1;
  89874. if ((i + 1) > points.elements.length - 1) {
  89875. p1 = points.elements[0];
  89876. }
  89877. else {
  89878. p1 = points.elements[i + 1];
  89879. }
  89880. positions.push(p.x, 0, p.y);
  89881. positions.push(p.x, -depth, p.y);
  89882. positions.push(p1.x, 0, p1.y);
  89883. positions.push(p1.x, -depth, p1.y);
  89884. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89885. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89886. var v3 = v2.subtract(v1);
  89887. var v4 = new BABYLON.Vector3(0, 1, 0);
  89888. var vn = BABYLON.Vector3.Cross(v3, v4);
  89889. vn = vn.normalize();
  89890. uvs.push(ulength / bounds.width, 0);
  89891. uvs.push(ulength / bounds.width, 1);
  89892. ulength += v3.length();
  89893. uvs.push((ulength / bounds.width), 0);
  89894. uvs.push((ulength / bounds.width), 1);
  89895. if (!flip) {
  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. normals.push(-vn.x, -vn.y, -vn.z);
  89900. indices.push(StartIndex);
  89901. indices.push(StartIndex + 1);
  89902. indices.push(StartIndex + 2);
  89903. indices.push(StartIndex + 1);
  89904. indices.push(StartIndex + 3);
  89905. indices.push(StartIndex + 2);
  89906. }
  89907. else {
  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. normals.push(vn.x, vn.y, vn.z);
  89912. indices.push(StartIndex);
  89913. indices.push(StartIndex + 2);
  89914. indices.push(StartIndex + 1);
  89915. indices.push(StartIndex + 1);
  89916. indices.push(StartIndex + 2);
  89917. indices.push(StartIndex + 3);
  89918. }
  89919. StartIndex += 4;
  89920. }
  89921. ;
  89922. };
  89923. return PolygonMeshBuilder;
  89924. }());
  89925. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89926. })(BABYLON || (BABYLON = {}));
  89927. //# sourceMappingURL=babylon.polygonMesh.js.map
  89928. var BABYLON;
  89929. (function (BABYLON) {
  89930. // Unique ID when we import meshes from Babylon to CSG
  89931. var currentCSGMeshId = 0;
  89932. // # class Vertex
  89933. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89934. // one to provide additional features like texture coordinates and vertex
  89935. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89936. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89937. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89938. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89939. // is not used anywhere else.
  89940. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89941. var Vertex = /** @class */ (function () {
  89942. function Vertex(pos, normal, uv) {
  89943. this.pos = pos;
  89944. this.normal = normal;
  89945. this.uv = uv;
  89946. }
  89947. Vertex.prototype.clone = function () {
  89948. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89949. };
  89950. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89951. // orientation of a polygon is flipped.
  89952. Vertex.prototype.flip = function () {
  89953. this.normal = this.normal.scale(-1);
  89954. };
  89955. // Create a new vertex between this vertex and `other` by linearly
  89956. // interpolating all properties using a parameter of `t`. Subclasses should
  89957. // override this to interpolate additional properties.
  89958. Vertex.prototype.interpolate = function (other, t) {
  89959. 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));
  89960. };
  89961. return Vertex;
  89962. }());
  89963. // # class Plane
  89964. // Represents a plane in 3D space.
  89965. var Plane = /** @class */ (function () {
  89966. function Plane(normal, w) {
  89967. this.normal = normal;
  89968. this.w = w;
  89969. }
  89970. Plane.FromPoints = function (a, b, c) {
  89971. var v0 = c.subtract(a);
  89972. var v1 = b.subtract(a);
  89973. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  89974. return null;
  89975. }
  89976. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  89977. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  89978. };
  89979. Plane.prototype.clone = function () {
  89980. return new Plane(this.normal.clone(), this.w);
  89981. };
  89982. Plane.prototype.flip = function () {
  89983. this.normal.scaleInPlace(-1);
  89984. this.w = -this.w;
  89985. };
  89986. // Split `polygon` by this plane if needed, then put the polygon or polygon
  89987. // fragments in the appropriate lists. Coplanar polygons go into either
  89988. // `coplanarFront` or `coplanarBack` depending on their orientation with
  89989. // respect to this plane. Polygons in front or in back of this plane go into
  89990. // either `front` or `back`.
  89991. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  89992. var COPLANAR = 0;
  89993. var FRONT = 1;
  89994. var BACK = 2;
  89995. var SPANNING = 3;
  89996. // Classify each point as well as the entire polygon into one of the above
  89997. // four classes.
  89998. var polygonType = 0;
  89999. var types = [];
  90000. var i;
  90001. var t;
  90002. for (i = 0; i < polygon.vertices.length; i++) {
  90003. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  90004. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  90005. polygonType |= type;
  90006. types.push(type);
  90007. }
  90008. // Put the polygon in the correct list, splitting it when necessary.
  90009. switch (polygonType) {
  90010. case COPLANAR:
  90011. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  90012. break;
  90013. case FRONT:
  90014. front.push(polygon);
  90015. break;
  90016. case BACK:
  90017. back.push(polygon);
  90018. break;
  90019. case SPANNING:
  90020. var f = [], b = [];
  90021. for (i = 0; i < polygon.vertices.length; i++) {
  90022. var j = (i + 1) % polygon.vertices.length;
  90023. var ti = types[i], tj = types[j];
  90024. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  90025. if (ti !== BACK)
  90026. f.push(vi);
  90027. if (ti !== FRONT)
  90028. b.push(ti !== BACK ? vi.clone() : vi);
  90029. if ((ti | tj) === SPANNING) {
  90030. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  90031. var v = vi.interpolate(vj, t);
  90032. f.push(v);
  90033. b.push(v.clone());
  90034. }
  90035. }
  90036. var poly;
  90037. if (f.length >= 3) {
  90038. poly = new Polygon(f, polygon.shared);
  90039. if (poly.plane)
  90040. front.push(poly);
  90041. }
  90042. if (b.length >= 3) {
  90043. poly = new Polygon(b, polygon.shared);
  90044. if (poly.plane)
  90045. back.push(poly);
  90046. }
  90047. break;
  90048. }
  90049. };
  90050. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  90051. // point is on the plane.
  90052. Plane.EPSILON = 1e-5;
  90053. return Plane;
  90054. }());
  90055. // # class Polygon
  90056. // Represents a convex polygon. The vertices used to initialize a polygon must
  90057. // be coplanar and form a convex loop.
  90058. //
  90059. // Each convex polygon has a `shared` property, which is shared between all
  90060. // polygons that are clones of each other or were split from the same polygon.
  90061. // This can be used to define per-polygon properties (such as surface color).
  90062. var Polygon = /** @class */ (function () {
  90063. function Polygon(vertices, shared) {
  90064. this.vertices = vertices;
  90065. this.shared = shared;
  90066. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  90067. }
  90068. Polygon.prototype.clone = function () {
  90069. var vertices = this.vertices.map(function (v) { return v.clone(); });
  90070. return new Polygon(vertices, this.shared);
  90071. };
  90072. Polygon.prototype.flip = function () {
  90073. this.vertices.reverse().map(function (v) { v.flip(); });
  90074. this.plane.flip();
  90075. };
  90076. return Polygon;
  90077. }());
  90078. // # class Node
  90079. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  90080. // by picking a polygon to split along. That polygon (and all other coplanar
  90081. // polygons) are added directly to that node and the other polygons are added to
  90082. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  90083. // no distinction between internal and leaf nodes.
  90084. var Node = /** @class */ (function () {
  90085. function Node(polygons) {
  90086. this.plane = null;
  90087. this.front = null;
  90088. this.back = null;
  90089. this.polygons = new Array();
  90090. if (polygons) {
  90091. this.build(polygons);
  90092. }
  90093. }
  90094. Node.prototype.clone = function () {
  90095. var node = new Node();
  90096. node.plane = this.plane && this.plane.clone();
  90097. node.front = this.front && this.front.clone();
  90098. node.back = this.back && this.back.clone();
  90099. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  90100. return node;
  90101. };
  90102. // Convert solid space to empty space and empty space to solid space.
  90103. Node.prototype.invert = function () {
  90104. for (var i = 0; i < this.polygons.length; i++) {
  90105. this.polygons[i].flip();
  90106. }
  90107. if (this.plane) {
  90108. this.plane.flip();
  90109. }
  90110. if (this.front) {
  90111. this.front.invert();
  90112. }
  90113. if (this.back) {
  90114. this.back.invert();
  90115. }
  90116. var temp = this.front;
  90117. this.front = this.back;
  90118. this.back = temp;
  90119. };
  90120. // Recursively remove all polygons in `polygons` that are inside this BSP
  90121. // tree.
  90122. Node.prototype.clipPolygons = function (polygons) {
  90123. if (!this.plane)
  90124. return polygons.slice();
  90125. var front = new Array(), back = new Array();
  90126. for (var i = 0; i < polygons.length; i++) {
  90127. this.plane.splitPolygon(polygons[i], front, back, front, back);
  90128. }
  90129. if (this.front) {
  90130. front = this.front.clipPolygons(front);
  90131. }
  90132. if (this.back) {
  90133. back = this.back.clipPolygons(back);
  90134. }
  90135. else {
  90136. back = [];
  90137. }
  90138. return front.concat(back);
  90139. };
  90140. // Remove all polygons in this BSP tree that are inside the other BSP tree
  90141. // `bsp`.
  90142. Node.prototype.clipTo = function (bsp) {
  90143. this.polygons = bsp.clipPolygons(this.polygons);
  90144. if (this.front)
  90145. this.front.clipTo(bsp);
  90146. if (this.back)
  90147. this.back.clipTo(bsp);
  90148. };
  90149. // Return a list of all polygons in this BSP tree.
  90150. Node.prototype.allPolygons = function () {
  90151. var polygons = this.polygons.slice();
  90152. if (this.front)
  90153. polygons = polygons.concat(this.front.allPolygons());
  90154. if (this.back)
  90155. polygons = polygons.concat(this.back.allPolygons());
  90156. return polygons;
  90157. };
  90158. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  90159. // new polygons are filtered down to the bottom of the tree and become new
  90160. // nodes there. Each set of polygons is partitioned using the first polygon
  90161. // (no heuristic is used to pick a good split).
  90162. Node.prototype.build = function (polygons) {
  90163. if (!polygons.length)
  90164. return;
  90165. if (!this.plane)
  90166. this.plane = polygons[0].plane.clone();
  90167. var front = new Array(), back = new Array();
  90168. for (var i = 0; i < polygons.length; i++) {
  90169. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  90170. }
  90171. if (front.length) {
  90172. if (!this.front)
  90173. this.front = new Node();
  90174. this.front.build(front);
  90175. }
  90176. if (back.length) {
  90177. if (!this.back)
  90178. this.back = new Node();
  90179. this.back.build(back);
  90180. }
  90181. };
  90182. return Node;
  90183. }());
  90184. var CSG = /** @class */ (function () {
  90185. function CSG() {
  90186. this.polygons = new Array();
  90187. }
  90188. // Convert BABYLON.Mesh to BABYLON.CSG
  90189. CSG.FromMesh = function (mesh) {
  90190. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  90191. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  90192. if (mesh instanceof BABYLON.Mesh) {
  90193. mesh.computeWorldMatrix(true);
  90194. matrix = mesh.getWorldMatrix();
  90195. meshPosition = mesh.position.clone();
  90196. meshRotation = mesh.rotation.clone();
  90197. if (mesh.rotationQuaternion) {
  90198. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  90199. }
  90200. meshScaling = mesh.scaling.clone();
  90201. }
  90202. else {
  90203. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  90204. }
  90205. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90206. var subMeshes = mesh.subMeshes;
  90207. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  90208. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  90209. vertices = [];
  90210. for (var j = 0; j < 3; j++) {
  90211. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  90212. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  90213. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  90214. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  90215. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  90216. vertex = new Vertex(position, normal, uv);
  90217. vertices.push(vertex);
  90218. }
  90219. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  90220. // To handle the case of degenerated triangle
  90221. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  90222. if (polygon.plane)
  90223. polygons.push(polygon);
  90224. }
  90225. }
  90226. var csg = CSG.FromPolygons(polygons);
  90227. csg.matrix = matrix;
  90228. csg.position = meshPosition;
  90229. csg.rotation = meshRotation;
  90230. csg.scaling = meshScaling;
  90231. csg.rotationQuaternion = meshRotationQuaternion;
  90232. currentCSGMeshId++;
  90233. return csg;
  90234. };
  90235. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  90236. CSG.FromPolygons = function (polygons) {
  90237. var csg = new CSG();
  90238. csg.polygons = polygons;
  90239. return csg;
  90240. };
  90241. CSG.prototype.clone = function () {
  90242. var csg = new CSG();
  90243. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  90244. csg.copyTransformAttributes(this);
  90245. return csg;
  90246. };
  90247. CSG.prototype.union = function (csg) {
  90248. var a = new Node(this.clone().polygons);
  90249. var b = new Node(csg.clone().polygons);
  90250. a.clipTo(b);
  90251. b.clipTo(a);
  90252. b.invert();
  90253. b.clipTo(a);
  90254. b.invert();
  90255. a.build(b.allPolygons());
  90256. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90257. };
  90258. CSG.prototype.unionInPlace = function (csg) {
  90259. var a = new Node(this.polygons);
  90260. var b = new Node(csg.polygons);
  90261. a.clipTo(b);
  90262. b.clipTo(a);
  90263. b.invert();
  90264. b.clipTo(a);
  90265. b.invert();
  90266. a.build(b.allPolygons());
  90267. this.polygons = a.allPolygons();
  90268. };
  90269. CSG.prototype.subtract = function (csg) {
  90270. var a = new Node(this.clone().polygons);
  90271. var b = new Node(csg.clone().polygons);
  90272. a.invert();
  90273. a.clipTo(b);
  90274. b.clipTo(a);
  90275. b.invert();
  90276. b.clipTo(a);
  90277. b.invert();
  90278. a.build(b.allPolygons());
  90279. a.invert();
  90280. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90281. };
  90282. CSG.prototype.subtractInPlace = function (csg) {
  90283. var a = new Node(this.polygons);
  90284. var b = new Node(csg.polygons);
  90285. a.invert();
  90286. a.clipTo(b);
  90287. b.clipTo(a);
  90288. b.invert();
  90289. b.clipTo(a);
  90290. b.invert();
  90291. a.build(b.allPolygons());
  90292. a.invert();
  90293. this.polygons = a.allPolygons();
  90294. };
  90295. CSG.prototype.intersect = function (csg) {
  90296. var a = new Node(this.clone().polygons);
  90297. var b = new Node(csg.clone().polygons);
  90298. a.invert();
  90299. b.clipTo(a);
  90300. b.invert();
  90301. a.clipTo(b);
  90302. b.clipTo(a);
  90303. a.build(b.allPolygons());
  90304. a.invert();
  90305. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90306. };
  90307. CSG.prototype.intersectInPlace = function (csg) {
  90308. var a = new Node(this.polygons);
  90309. var b = new Node(csg.polygons);
  90310. a.invert();
  90311. b.clipTo(a);
  90312. b.invert();
  90313. a.clipTo(b);
  90314. b.clipTo(a);
  90315. a.build(b.allPolygons());
  90316. a.invert();
  90317. this.polygons = a.allPolygons();
  90318. };
  90319. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  90320. // not modified.
  90321. CSG.prototype.inverse = function () {
  90322. var csg = this.clone();
  90323. csg.inverseInPlace();
  90324. return csg;
  90325. };
  90326. CSG.prototype.inverseInPlace = function () {
  90327. this.polygons.map(function (p) { p.flip(); });
  90328. };
  90329. // This is used to keep meshes transformations so they can be restored
  90330. // when we build back a Babylon Mesh
  90331. // NB : All CSG operations are performed in world coordinates
  90332. CSG.prototype.copyTransformAttributes = function (csg) {
  90333. this.matrix = csg.matrix;
  90334. this.position = csg.position;
  90335. this.rotation = csg.rotation;
  90336. this.scaling = csg.scaling;
  90337. this.rotationQuaternion = csg.rotationQuaternion;
  90338. return this;
  90339. };
  90340. // Build Raw mesh from CSG
  90341. // Coordinates here are in world space
  90342. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  90343. var matrix = this.matrix.clone();
  90344. matrix.invert();
  90345. 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;
  90346. if (keepSubMeshes) {
  90347. // Sort Polygons, since subMeshes are indices range
  90348. polygons.sort(function (a, b) {
  90349. if (a.shared.meshId === b.shared.meshId) {
  90350. return a.shared.subMeshId - b.shared.subMeshId;
  90351. }
  90352. else {
  90353. return a.shared.meshId - b.shared.meshId;
  90354. }
  90355. });
  90356. }
  90357. for (var i = 0, il = polygons.length; i < il; i++) {
  90358. polygon = polygons[i];
  90359. // Building SubMeshes
  90360. if (!subMesh_dict[polygon.shared.meshId]) {
  90361. subMesh_dict[polygon.shared.meshId] = {};
  90362. }
  90363. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  90364. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  90365. indexStart: +Infinity,
  90366. indexEnd: -Infinity,
  90367. materialIndex: polygon.shared.materialIndex
  90368. };
  90369. }
  90370. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  90371. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  90372. polygonIndices[0] = 0;
  90373. polygonIndices[1] = j - 1;
  90374. polygonIndices[2] = j;
  90375. for (var k = 0; k < 3; k++) {
  90376. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  90377. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  90378. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  90379. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  90380. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  90381. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  90382. // Check if 2 points can be merged
  90383. if (!(typeof vertex_idx !== 'undefined' &&
  90384. normals[vertex_idx * 3] === localNormal.x &&
  90385. normals[vertex_idx * 3 + 1] === localNormal.y &&
  90386. normals[vertex_idx * 3 + 2] === localNormal.z &&
  90387. uvs[vertex_idx * 2] === uv.x &&
  90388. uvs[vertex_idx * 2 + 1] === uv.y)) {
  90389. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  90390. uvs.push(uv.x, uv.y);
  90391. normals.push(normal.x, normal.y, normal.z);
  90392. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  90393. }
  90394. indices.push(vertex_idx);
  90395. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  90396. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  90397. currentIndex++;
  90398. }
  90399. }
  90400. }
  90401. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  90402. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  90403. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  90404. mesh.setIndices(indices, null);
  90405. if (keepSubMeshes) {
  90406. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  90407. var materialIndexOffset = 0, materialMaxIndex;
  90408. mesh.subMeshes = new Array();
  90409. for (var m in subMesh_dict) {
  90410. materialMaxIndex = -1;
  90411. for (var sm in subMesh_dict[m]) {
  90412. subMesh_obj = subMesh_dict[m][sm];
  90413. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  90414. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  90415. }
  90416. materialIndexOffset += ++materialMaxIndex;
  90417. }
  90418. }
  90419. return mesh;
  90420. };
  90421. // Build Mesh from CSG taking material and transforms into account
  90422. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  90423. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  90424. mesh.material = material;
  90425. mesh.position.copyFrom(this.position);
  90426. mesh.rotation.copyFrom(this.rotation);
  90427. if (this.rotationQuaternion) {
  90428. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  90429. }
  90430. mesh.scaling.copyFrom(this.scaling);
  90431. mesh.computeWorldMatrix(true);
  90432. return mesh;
  90433. };
  90434. return CSG;
  90435. }());
  90436. BABYLON.CSG = CSG;
  90437. })(BABYLON || (BABYLON = {}));
  90438. //# sourceMappingURL=babylon.csg.js.map
  90439. var BABYLON;
  90440. (function (BABYLON) {
  90441. /**
  90442. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90443. * It controls one of the indiviual texture used in the effect.
  90444. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90445. */
  90446. var LensFlare = /** @class */ (function () {
  90447. /**
  90448. * Instantiates a new Lens Flare.
  90449. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90450. * It controls one of the indiviual texture used in the effect.
  90451. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90452. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  90453. * @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.
  90454. * @param color Define the lens color
  90455. * @param imgUrl Define the lens texture url
  90456. * @param system Define the `lensFlareSystem` this flare is part of
  90457. */
  90458. function LensFlare(
  90459. /**
  90460. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  90461. */
  90462. size,
  90463. /**
  90464. * 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.
  90465. */
  90466. position, color, imgUrl, system) {
  90467. this.size = size;
  90468. this.position = position;
  90469. /**
  90470. * Define the alpha mode to render this particular lens.
  90471. */
  90472. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90473. this.color = color || new BABYLON.Color3(1, 1, 1);
  90474. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  90475. this._system = system;
  90476. system.lensFlares.push(this);
  90477. }
  90478. /**
  90479. * Creates a new Lens Flare.
  90480. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90481. * It controls one of the indiviual texture used in the effect.
  90482. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90483. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  90484. * @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.
  90485. * @param color Define the lens color
  90486. * @param imgUrl Define the lens texture url
  90487. * @param system Define the `lensFlareSystem` this flare is part of
  90488. * @returns The newly created Lens Flare
  90489. */
  90490. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  90491. return new LensFlare(size, position, color, imgUrl, system);
  90492. };
  90493. /**
  90494. * Dispose and release the lens flare with its associated resources.
  90495. */
  90496. LensFlare.prototype.dispose = function () {
  90497. if (this.texture) {
  90498. this.texture.dispose();
  90499. }
  90500. // Remove from scene
  90501. var index = this._system.lensFlares.indexOf(this);
  90502. this._system.lensFlares.splice(index, 1);
  90503. };
  90504. ;
  90505. return LensFlare;
  90506. }());
  90507. BABYLON.LensFlare = LensFlare;
  90508. })(BABYLON || (BABYLON = {}));
  90509. //# sourceMappingURL=babylon.lensFlare.js.map
  90510. var BABYLON;
  90511. (function (BABYLON) {
  90512. // Adds the parser to the scene parsers.
  90513. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  90514. // Lens flares
  90515. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  90516. if (!container.lensFlareSystems) {
  90517. container.lensFlareSystems = new Array();
  90518. }
  90519. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  90520. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  90521. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  90522. container.lensFlareSystems.push(lf);
  90523. }
  90524. }
  90525. });
  90526. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  90527. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90528. if (this.lensFlareSystems[index].name === name) {
  90529. return this.lensFlareSystems[index];
  90530. }
  90531. }
  90532. return null;
  90533. };
  90534. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  90535. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90536. if (this.lensFlareSystems[index].id === id) {
  90537. return this.lensFlareSystems[index];
  90538. }
  90539. }
  90540. return null;
  90541. };
  90542. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  90543. var index = this.lensFlareSystems.indexOf(toRemove);
  90544. if (index !== -1) {
  90545. this.lensFlareSystems.splice(index, 1);
  90546. }
  90547. return index;
  90548. };
  90549. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  90550. this.lensFlareSystems.push(newLensFlareSystem);
  90551. };
  90552. /**
  90553. * Defines the lens flare scene component responsible to manage any lens flares
  90554. * in a given scene.
  90555. */
  90556. var LensFlareSystemSceneComponent = /** @class */ (function () {
  90557. /**
  90558. * Creates a new instance of the component for the given scene
  90559. * @param scene Defines the scene to register the component in
  90560. */
  90561. function LensFlareSystemSceneComponent(scene) {
  90562. /**
  90563. * The component name helpfull to identify the component in the list of scene components.
  90564. */
  90565. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  90566. this.scene = scene;
  90567. scene.lensFlareSystems = new Array();
  90568. }
  90569. /**
  90570. * Registers the component in a given scene
  90571. */
  90572. LensFlareSystemSceneComponent.prototype.register = function () {
  90573. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  90574. };
  90575. /**
  90576. * Rebuilds the elements related to this component in case of
  90577. * context lost for instance.
  90578. */
  90579. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  90580. // Nothing to do for lens flare
  90581. };
  90582. /**
  90583. * Adds all the element from the container to the scene
  90584. * @param container the container holding the elements
  90585. */
  90586. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  90587. var _this = this;
  90588. if (!container.lensFlareSystems) {
  90589. return;
  90590. }
  90591. container.lensFlareSystems.forEach(function (o) {
  90592. _this.scene.addLensFlareSystem(o);
  90593. });
  90594. };
  90595. /**
  90596. * Removes all the elements in the container from the scene
  90597. * @param container contains the elements to remove
  90598. */
  90599. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  90600. var _this = this;
  90601. if (!container.lensFlareSystems) {
  90602. return;
  90603. }
  90604. container.lensFlareSystems.forEach(function (o) {
  90605. _this.scene.removeLensFlareSystem(o);
  90606. });
  90607. };
  90608. /**
  90609. * Serializes the component data to the specified json object
  90610. * @param serializationObject The object to serialize to
  90611. */
  90612. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  90613. // Lens flares
  90614. serializationObject.lensFlareSystems = [];
  90615. var lensFlareSystems = this.scene.lensFlareSystems;
  90616. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  90617. var lensFlareSystem = lensFlareSystems_1[_i];
  90618. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  90619. }
  90620. };
  90621. /**
  90622. * Disposes the component and the associated ressources.
  90623. */
  90624. LensFlareSystemSceneComponent.prototype.dispose = function () {
  90625. var lensFlareSystems = this.scene.lensFlareSystems;
  90626. while (lensFlareSystems.length) {
  90627. lensFlareSystems[0].dispose();
  90628. }
  90629. };
  90630. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  90631. // Lens flares
  90632. if (this.scene.lensFlaresEnabled) {
  90633. var lensFlareSystems = this.scene.lensFlareSystems;
  90634. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90635. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  90636. var lensFlareSystem = lensFlareSystems_2[_i];
  90637. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  90638. lensFlareSystem.render();
  90639. }
  90640. }
  90641. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90642. }
  90643. };
  90644. return LensFlareSystemSceneComponent;
  90645. }());
  90646. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  90647. })(BABYLON || (BABYLON = {}));
  90648. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  90649. var BABYLON;
  90650. (function (BABYLON) {
  90651. /**
  90652. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90653. * It is usually composed of several `BABYLON.lensFlare`.
  90654. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90655. */
  90656. var LensFlareSystem = /** @class */ (function () {
  90657. /**
  90658. * Instantiates a lens flare system.
  90659. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90660. * It is usually composed of several `BABYLON.lensFlare`.
  90661. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90662. * @param name Define the name of the lens flare system in the scene
  90663. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  90664. * @param scene Define the scene the lens flare system belongs to
  90665. */
  90666. function LensFlareSystem(
  90667. /**
  90668. * Define the name of the lens flare system
  90669. */
  90670. name, emitter, scene) {
  90671. this.name = name;
  90672. /**
  90673. * List of lens flares used in this system.
  90674. */
  90675. this.lensFlares = new Array();
  90676. /**
  90677. * Define a limit from the border the lens flare can be visible.
  90678. */
  90679. this.borderLimit = 300;
  90680. /**
  90681. * Define a viewport border we do not want to see the lens flare in.
  90682. */
  90683. this.viewportBorder = 0;
  90684. /**
  90685. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  90686. */
  90687. this.layerMask = 0x0FFFFFFF;
  90688. this._vertexBuffers = {};
  90689. this._isEnabled = true;
  90690. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90691. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  90692. if (!component) {
  90693. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  90694. scene._addComponent(component);
  90695. }
  90696. this._emitter = emitter;
  90697. this.id = name;
  90698. scene.lensFlareSystems.push(this);
  90699. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  90700. var engine = scene.getEngine();
  90701. // VBO
  90702. var vertices = [];
  90703. vertices.push(1, 1);
  90704. vertices.push(-1, 1);
  90705. vertices.push(-1, -1);
  90706. vertices.push(1, -1);
  90707. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90708. // Indices
  90709. var indices = [];
  90710. indices.push(0);
  90711. indices.push(1);
  90712. indices.push(2);
  90713. indices.push(0);
  90714. indices.push(2);
  90715. indices.push(3);
  90716. this._indexBuffer = engine.createIndexBuffer(indices);
  90717. // Effects
  90718. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  90719. }
  90720. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  90721. /**
  90722. * Define if the lens flare system is enabled.
  90723. */
  90724. get: function () {
  90725. return this._isEnabled;
  90726. },
  90727. set: function (value) {
  90728. this._isEnabled = value;
  90729. },
  90730. enumerable: true,
  90731. configurable: true
  90732. });
  90733. /**
  90734. * Get the scene the effects belongs to.
  90735. * @returns the scene holding the lens flare system
  90736. */
  90737. LensFlareSystem.prototype.getScene = function () {
  90738. return this._scene;
  90739. };
  90740. /**
  90741. * Get the emitter of the lens flare system.
  90742. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90743. * @returns the emitter of the lens flare system
  90744. */
  90745. LensFlareSystem.prototype.getEmitter = function () {
  90746. return this._emitter;
  90747. };
  90748. /**
  90749. * Set the emitter of the lens flare system.
  90750. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90751. * @param newEmitter Define the new emitter of the system
  90752. */
  90753. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  90754. this._emitter = newEmitter;
  90755. };
  90756. /**
  90757. * Get the lens flare system emitter position.
  90758. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  90759. * @returns the position
  90760. */
  90761. LensFlareSystem.prototype.getEmitterPosition = function () {
  90762. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  90763. };
  90764. /**
  90765. * @hidden
  90766. */
  90767. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  90768. var position = this.getEmitterPosition();
  90769. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  90770. this._positionX = position.x;
  90771. this._positionY = position.y;
  90772. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  90773. if (this.viewportBorder > 0) {
  90774. globalViewport.x -= this.viewportBorder;
  90775. globalViewport.y -= this.viewportBorder;
  90776. globalViewport.width += this.viewportBorder * 2;
  90777. globalViewport.height += this.viewportBorder * 2;
  90778. position.x += this.viewportBorder;
  90779. position.y += this.viewportBorder;
  90780. this._positionX += this.viewportBorder;
  90781. this._positionY += this.viewportBorder;
  90782. }
  90783. if (position.z > 0) {
  90784. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  90785. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  90786. return true;
  90787. }
  90788. return true;
  90789. }
  90790. return false;
  90791. };
  90792. /** @hidden */
  90793. LensFlareSystem.prototype._isVisible = function () {
  90794. if (!this._isEnabled || !this._scene.activeCamera) {
  90795. return false;
  90796. }
  90797. var emitterPosition = this.getEmitterPosition();
  90798. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  90799. var distance = direction.length();
  90800. direction.normalize();
  90801. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  90802. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  90803. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  90804. };
  90805. /**
  90806. * @hidden
  90807. */
  90808. LensFlareSystem.prototype.render = function () {
  90809. if (!this._effect.isReady() || !this._scene.activeCamera)
  90810. return false;
  90811. var engine = this._scene.getEngine();
  90812. var viewport = this._scene.activeCamera.viewport;
  90813. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  90814. // Position
  90815. if (!this.computeEffectivePosition(globalViewport)) {
  90816. return false;
  90817. }
  90818. // Visibility
  90819. if (!this._isVisible()) {
  90820. return false;
  90821. }
  90822. // Intensity
  90823. var awayX;
  90824. var awayY;
  90825. if (this._positionX < this.borderLimit + globalViewport.x) {
  90826. awayX = this.borderLimit + globalViewport.x - this._positionX;
  90827. }
  90828. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  90829. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  90830. }
  90831. else {
  90832. awayX = 0;
  90833. }
  90834. if (this._positionY < this.borderLimit + globalViewport.y) {
  90835. awayY = this.borderLimit + globalViewport.y - this._positionY;
  90836. }
  90837. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  90838. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  90839. }
  90840. else {
  90841. awayY = 0;
  90842. }
  90843. var away = (awayX > awayY) ? awayX : awayY;
  90844. away -= this.viewportBorder;
  90845. if (away > this.borderLimit) {
  90846. away = this.borderLimit;
  90847. }
  90848. var intensity = 1.0 - (away / this.borderLimit);
  90849. if (intensity < 0) {
  90850. return false;
  90851. }
  90852. if (intensity > 1.0) {
  90853. intensity = 1.0;
  90854. }
  90855. if (this.viewportBorder > 0) {
  90856. globalViewport.x += this.viewportBorder;
  90857. globalViewport.y += this.viewportBorder;
  90858. globalViewport.width -= this.viewportBorder * 2;
  90859. globalViewport.height -= this.viewportBorder * 2;
  90860. this._positionX -= this.viewportBorder;
  90861. this._positionY -= this.viewportBorder;
  90862. }
  90863. // Position
  90864. var centerX = globalViewport.x + globalViewport.width / 2;
  90865. var centerY = globalViewport.y + globalViewport.height / 2;
  90866. var distX = centerX - this._positionX;
  90867. var distY = centerY - this._positionY;
  90868. // Effects
  90869. engine.enableEffect(this._effect);
  90870. engine.setState(false);
  90871. engine.setDepthBuffer(false);
  90872. // VBOs
  90873. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  90874. // Flares
  90875. for (var index = 0; index < this.lensFlares.length; index++) {
  90876. var flare = this.lensFlares[index];
  90877. engine.setAlphaMode(flare.alphaMode);
  90878. var x = centerX - (distX * flare.position);
  90879. var y = centerY - (distY * flare.position);
  90880. var cw = flare.size;
  90881. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  90882. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  90883. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  90884. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  90885. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  90886. // Texture
  90887. this._effect.setTexture("textureSampler", flare.texture);
  90888. // Color
  90889. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  90890. // Draw order
  90891. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90892. }
  90893. engine.setDepthBuffer(true);
  90894. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90895. return true;
  90896. };
  90897. /**
  90898. * Dispose and release the lens flare with its associated resources.
  90899. */
  90900. LensFlareSystem.prototype.dispose = function () {
  90901. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90902. if (vertexBuffer) {
  90903. vertexBuffer.dispose();
  90904. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90905. }
  90906. if (this._indexBuffer) {
  90907. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90908. this._indexBuffer = null;
  90909. }
  90910. while (this.lensFlares.length) {
  90911. this.lensFlares[0].dispose();
  90912. }
  90913. // Remove from scene
  90914. var index = this._scene.lensFlareSystems.indexOf(this);
  90915. this._scene.lensFlareSystems.splice(index, 1);
  90916. };
  90917. /**
  90918. * Parse a lens flare system from a JSON repressentation
  90919. * @param parsedLensFlareSystem Define the JSON to parse
  90920. * @param scene Define the scene the parsed system should be instantiated in
  90921. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  90922. * @returns the parsed system
  90923. */
  90924. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  90925. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  90926. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  90927. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  90928. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  90929. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  90930. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  90931. var parsedFlare = parsedLensFlareSystem.flares[index];
  90932. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  90933. }
  90934. return lensFlareSystem;
  90935. };
  90936. /**
  90937. * Serialize the current Lens Flare System into a JSON representation.
  90938. * @returns the serialized JSON
  90939. */
  90940. LensFlareSystem.prototype.serialize = function () {
  90941. var serializationObject = {};
  90942. serializationObject.id = this.id;
  90943. serializationObject.name = this.name;
  90944. serializationObject.emitterId = this.getEmitter().id;
  90945. serializationObject.borderLimit = this.borderLimit;
  90946. serializationObject.flares = [];
  90947. for (var index = 0; index < this.lensFlares.length; index++) {
  90948. var flare = this.lensFlares[index];
  90949. serializationObject.flares.push({
  90950. size: flare.size,
  90951. position: flare.position,
  90952. color: flare.color.asArray(),
  90953. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  90954. });
  90955. }
  90956. return serializationObject;
  90957. };
  90958. return LensFlareSystem;
  90959. }());
  90960. BABYLON.LensFlareSystem = LensFlareSystem;
  90961. })(BABYLON || (BABYLON = {}));
  90962. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  90963. var BABYLON;
  90964. (function (BABYLON) {
  90965. /**
  90966. * This is a holder class for the physics joint created by the physics plugin.
  90967. * It holds a set of functions to control the underlying joint.
  90968. */
  90969. var PhysicsJoint = /** @class */ (function () {
  90970. function PhysicsJoint(type, jointData) {
  90971. this.type = type;
  90972. this.jointData = jointData;
  90973. jointData.nativeParams = jointData.nativeParams || {};
  90974. }
  90975. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  90976. get: function () {
  90977. return this._physicsJoint;
  90978. },
  90979. set: function (newJoint) {
  90980. if (this._physicsJoint) {
  90981. //remove from the wolrd
  90982. }
  90983. this._physicsJoint = newJoint;
  90984. },
  90985. enumerable: true,
  90986. configurable: true
  90987. });
  90988. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  90989. set: function (physicsPlugin) {
  90990. this._physicsPlugin = physicsPlugin;
  90991. },
  90992. enumerable: true,
  90993. configurable: true
  90994. });
  90995. /**
  90996. * Execute a function that is physics-plugin specific.
  90997. * @param {Function} func the function that will be executed.
  90998. * It accepts two parameters: the physics world and the physics joint.
  90999. */
  91000. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  91001. func(this._physicsPlugin.world, this._physicsJoint);
  91002. };
  91003. //TODO check if the native joints are the same
  91004. //Joint Types
  91005. PhysicsJoint.DistanceJoint = 0;
  91006. PhysicsJoint.HingeJoint = 1;
  91007. PhysicsJoint.BallAndSocketJoint = 2;
  91008. PhysicsJoint.WheelJoint = 3;
  91009. PhysicsJoint.SliderJoint = 4;
  91010. //OIMO
  91011. PhysicsJoint.PrismaticJoint = 5;
  91012. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  91013. PhysicsJoint.UniversalJoint = 6;
  91014. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  91015. //Cannon
  91016. //Similar to a Ball-Joint. Different in params
  91017. PhysicsJoint.PointToPointJoint = 8;
  91018. //Cannon only at the moment
  91019. PhysicsJoint.SpringJoint = 9;
  91020. PhysicsJoint.LockJoint = 10;
  91021. return PhysicsJoint;
  91022. }());
  91023. BABYLON.PhysicsJoint = PhysicsJoint;
  91024. /**
  91025. * A class representing a physics distance joint.
  91026. */
  91027. var DistanceJoint = /** @class */ (function (_super) {
  91028. __extends(DistanceJoint, _super);
  91029. function DistanceJoint(jointData) {
  91030. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  91031. }
  91032. /**
  91033. * Update the predefined distance.
  91034. */
  91035. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  91036. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  91037. };
  91038. return DistanceJoint;
  91039. }(PhysicsJoint));
  91040. BABYLON.DistanceJoint = DistanceJoint;
  91041. var MotorEnabledJoint = /** @class */ (function (_super) {
  91042. __extends(MotorEnabledJoint, _super);
  91043. function MotorEnabledJoint(type, jointData) {
  91044. return _super.call(this, type, jointData) || this;
  91045. }
  91046. /**
  91047. * Set the motor values.
  91048. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91049. * @param {number} force the force to apply
  91050. * @param {number} maxForce max force for this motor.
  91051. */
  91052. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  91053. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91054. };
  91055. /**
  91056. * Set the motor's limits.
  91057. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91058. */
  91059. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91060. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91061. };
  91062. return MotorEnabledJoint;
  91063. }(PhysicsJoint));
  91064. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  91065. /**
  91066. * This class represents a single hinge physics joint
  91067. */
  91068. var HingeJoint = /** @class */ (function (_super) {
  91069. __extends(HingeJoint, _super);
  91070. function HingeJoint(jointData) {
  91071. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  91072. }
  91073. /**
  91074. * Set the motor values.
  91075. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91076. * @param {number} force the force to apply
  91077. * @param {number} maxForce max force for this motor.
  91078. */
  91079. HingeJoint.prototype.setMotor = function (force, maxForce) {
  91080. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91081. };
  91082. /**
  91083. * Set the motor's limits.
  91084. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91085. */
  91086. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91087. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91088. };
  91089. return HingeJoint;
  91090. }(MotorEnabledJoint));
  91091. BABYLON.HingeJoint = HingeJoint;
  91092. /**
  91093. * This class represents a dual hinge physics joint (same as wheel joint)
  91094. */
  91095. var Hinge2Joint = /** @class */ (function (_super) {
  91096. __extends(Hinge2Joint, _super);
  91097. function Hinge2Joint(jointData) {
  91098. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  91099. }
  91100. /**
  91101. * Set the motor values.
  91102. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91103. * @param {number} force the force to apply
  91104. * @param {number} maxForce max force for this motor.
  91105. * @param {motorIndex} the motor's index, 0 or 1.
  91106. */
  91107. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  91108. if (motorIndex === void 0) { motorIndex = 0; }
  91109. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  91110. };
  91111. /**
  91112. * Set the motor limits.
  91113. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91114. * @param {number} upperLimit the upper limit
  91115. * @param {number} lowerLimit lower limit
  91116. * @param {motorIndex} the motor's index, 0 or 1.
  91117. */
  91118. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  91119. if (motorIndex === void 0) { motorIndex = 0; }
  91120. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  91121. };
  91122. return Hinge2Joint;
  91123. }(MotorEnabledJoint));
  91124. BABYLON.Hinge2Joint = Hinge2Joint;
  91125. })(BABYLON || (BABYLON = {}));
  91126. //# sourceMappingURL=babylon.physicsJoint.js.map
  91127. var BABYLON;
  91128. (function (BABYLON) {
  91129. var PhysicsImpostor = /** @class */ (function () {
  91130. function PhysicsImpostor(object, type, _options, _scene) {
  91131. if (_options === void 0) { _options = { mass: 0 }; }
  91132. var _this = this;
  91133. this.object = object;
  91134. this.type = type;
  91135. this._options = _options;
  91136. this._scene = _scene;
  91137. this._bodyUpdateRequired = false;
  91138. this._onBeforePhysicsStepCallbacks = new Array();
  91139. this._onAfterPhysicsStepCallbacks = new Array();
  91140. this._onPhysicsCollideCallbacks = [];
  91141. this._deltaPosition = BABYLON.Vector3.Zero();
  91142. this._isDisposed = false;
  91143. //temp variables for parent rotation calculations
  91144. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  91145. this._tmpQuat = new BABYLON.Quaternion();
  91146. this._tmpQuat2 = new BABYLON.Quaternion();
  91147. /**
  91148. * this function is executed by the physics engine.
  91149. */
  91150. this.beforeStep = function () {
  91151. if (!_this._physicsEngine) {
  91152. return;
  91153. }
  91154. _this.object.translate(_this._deltaPosition, -1);
  91155. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  91156. _this.object.computeWorldMatrix(false);
  91157. if (_this.object.parent && _this.object.rotationQuaternion) {
  91158. _this.getParentsRotation();
  91159. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  91160. }
  91161. else {
  91162. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  91163. }
  91164. if (!_this._options.disableBidirectionalTransformation) {
  91165. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  91166. }
  91167. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  91168. func(_this);
  91169. });
  91170. };
  91171. /**
  91172. * this function is executed by the physics engine.
  91173. */
  91174. this.afterStep = function () {
  91175. if (!_this._physicsEngine) {
  91176. return;
  91177. }
  91178. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  91179. func(_this);
  91180. });
  91181. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  91182. // object has now its world rotation. needs to be converted to local.
  91183. if (_this.object.parent && _this.object.rotationQuaternion) {
  91184. _this.getParentsRotation();
  91185. _this._tmpQuat.conjugateInPlace();
  91186. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  91187. }
  91188. // take the position set and make it the absolute position of this object.
  91189. _this.object.setAbsolutePosition(_this.object.position);
  91190. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  91191. _this.object.translate(_this._deltaPosition, 1);
  91192. };
  91193. /**
  91194. * Legacy collision detection event support
  91195. */
  91196. this.onCollideEvent = null;
  91197. //event and body object due to cannon's event-based architecture.
  91198. this.onCollide = function (e) {
  91199. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  91200. return;
  91201. }
  91202. if (!_this._physicsEngine) {
  91203. return;
  91204. }
  91205. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  91206. if (otherImpostor) {
  91207. // Legacy collision detection event support
  91208. if (_this.onCollideEvent) {
  91209. _this.onCollideEvent(_this, otherImpostor);
  91210. }
  91211. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  91212. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  91213. }).forEach(function (obj) {
  91214. obj.callback(_this, otherImpostor);
  91215. });
  91216. }
  91217. };
  91218. //sanity check!
  91219. if (!this.object) {
  91220. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  91221. return;
  91222. }
  91223. //legacy support for old syntax.
  91224. if (!this._scene && object.getScene) {
  91225. this._scene = object.getScene();
  91226. }
  91227. if (!this._scene) {
  91228. return;
  91229. }
  91230. this._physicsEngine = this._scene.getPhysicsEngine();
  91231. if (!this._physicsEngine) {
  91232. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  91233. }
  91234. else {
  91235. //set the object's quaternion, if not set
  91236. if (!this.object.rotationQuaternion) {
  91237. if (this.object.rotation) {
  91238. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  91239. }
  91240. else {
  91241. this.object.rotationQuaternion = new BABYLON.Quaternion();
  91242. }
  91243. }
  91244. //default options params
  91245. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  91246. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  91247. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  91248. this._joints = [];
  91249. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  91250. if (!this.object.parent || this._options.ignoreParent) {
  91251. this._init();
  91252. }
  91253. else if (this.object.parent.physicsImpostor) {
  91254. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  91255. }
  91256. }
  91257. }
  91258. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  91259. get: function () {
  91260. return this._isDisposed;
  91261. },
  91262. enumerable: true,
  91263. configurable: true
  91264. });
  91265. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  91266. get: function () {
  91267. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  91268. },
  91269. set: function (value) {
  91270. this.setMass(value);
  91271. },
  91272. enumerable: true,
  91273. configurable: true
  91274. });
  91275. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  91276. get: function () {
  91277. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  91278. },
  91279. set: function (value) {
  91280. if (!this._physicsEngine) {
  91281. return;
  91282. }
  91283. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  91284. },
  91285. enumerable: true,
  91286. configurable: true
  91287. });
  91288. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  91289. get: function () {
  91290. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  91291. },
  91292. set: function (value) {
  91293. if (!this._physicsEngine) {
  91294. return;
  91295. }
  91296. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  91297. },
  91298. enumerable: true,
  91299. configurable: true
  91300. });
  91301. /**
  91302. * This function will completly initialize this impostor.
  91303. * It will create a new body - but only if this mesh has no parent.
  91304. * If it has, this impostor will not be used other than to define the impostor
  91305. * of the child mesh.
  91306. * @hidden
  91307. */
  91308. PhysicsImpostor.prototype._init = function () {
  91309. if (!this._physicsEngine) {
  91310. return;
  91311. }
  91312. this._physicsEngine.removeImpostor(this);
  91313. this.physicsBody = null;
  91314. this._parent = this._parent || this._getPhysicsParent();
  91315. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  91316. this._physicsEngine.addImpostor(this);
  91317. }
  91318. };
  91319. PhysicsImpostor.prototype._getPhysicsParent = function () {
  91320. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  91321. var parentMesh = this.object.parent;
  91322. return parentMesh.physicsImpostor;
  91323. }
  91324. return null;
  91325. };
  91326. /**
  91327. * Should a new body be generated.
  91328. */
  91329. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  91330. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  91331. };
  91332. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  91333. this.forceUpdate();
  91334. };
  91335. /**
  91336. * Force a regeneration of this or the parent's impostor's body.
  91337. * Use under cautious - This will remove all joints already implemented.
  91338. */
  91339. PhysicsImpostor.prototype.forceUpdate = function () {
  91340. this._init();
  91341. if (this.parent && !this._options.ignoreParent) {
  91342. this.parent.forceUpdate();
  91343. }
  91344. };
  91345. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  91346. /*public get mesh(): AbstractMesh {
  91347. return this._mesh;
  91348. }*/
  91349. /**
  91350. * Gets the body that holds this impostor. Either its own, or its parent.
  91351. */
  91352. get: function () {
  91353. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  91354. },
  91355. /**
  91356. * Set the physics body. Used mainly by the physics engine/plugin
  91357. */
  91358. set: function (physicsBody) {
  91359. if (this._physicsBody && this._physicsEngine) {
  91360. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  91361. }
  91362. this._physicsBody = physicsBody;
  91363. this.resetUpdateFlags();
  91364. },
  91365. enumerable: true,
  91366. configurable: true
  91367. });
  91368. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  91369. get: function () {
  91370. return !this._options.ignoreParent && this._parent ? this._parent : null;
  91371. },
  91372. set: function (value) {
  91373. this._parent = value;
  91374. },
  91375. enumerable: true,
  91376. configurable: true
  91377. });
  91378. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  91379. this._bodyUpdateRequired = false;
  91380. };
  91381. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  91382. if (this.object.getBoundingInfo) {
  91383. var q = this.object.rotationQuaternion;
  91384. //reset rotation
  91385. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  91386. //calculate the world matrix with no rotation
  91387. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91388. var boundingInfo = this.object.getBoundingInfo();
  91389. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  91390. //bring back the rotation
  91391. this.object.rotationQuaternion = q;
  91392. //calculate the world matrix with the new rotation
  91393. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91394. return size;
  91395. }
  91396. else {
  91397. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  91398. }
  91399. };
  91400. PhysicsImpostor.prototype.getObjectCenter = function () {
  91401. if (this.object.getBoundingInfo) {
  91402. var boundingInfo = this.object.getBoundingInfo();
  91403. return boundingInfo.boundingBox.centerWorld;
  91404. }
  91405. else {
  91406. return this.object.position;
  91407. }
  91408. };
  91409. /**
  91410. * Get a specific parametes from the options parameter.
  91411. */
  91412. PhysicsImpostor.prototype.getParam = function (paramName) {
  91413. return this._options[paramName];
  91414. };
  91415. /**
  91416. * Sets a specific parameter in the options given to the physics plugin
  91417. */
  91418. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  91419. this._options[paramName] = value;
  91420. this._bodyUpdateRequired = true;
  91421. };
  91422. /**
  91423. * Specifically change the body's mass option. Won't recreate the physics body object
  91424. */
  91425. PhysicsImpostor.prototype.setMass = function (mass) {
  91426. if (this.getParam("mass") !== mass) {
  91427. this.setParam("mass", mass);
  91428. }
  91429. if (this._physicsEngine) {
  91430. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  91431. }
  91432. };
  91433. PhysicsImpostor.prototype.getLinearVelocity = function () {
  91434. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  91435. };
  91436. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  91437. if (this._physicsEngine) {
  91438. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  91439. }
  91440. };
  91441. PhysicsImpostor.prototype.getAngularVelocity = function () {
  91442. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  91443. };
  91444. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  91445. if (this._physicsEngine) {
  91446. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  91447. }
  91448. };
  91449. /**
  91450. * Execute a function with the physics plugin native code.
  91451. * Provide a function the will have two variables - the world object and the physics body object.
  91452. */
  91453. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  91454. if (this._physicsEngine) {
  91455. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  91456. }
  91457. };
  91458. /**
  91459. * Register a function that will be executed before the physics world is stepping forward.
  91460. */
  91461. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  91462. this._onBeforePhysicsStepCallbacks.push(func);
  91463. };
  91464. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  91465. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  91466. if (index > -1) {
  91467. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  91468. }
  91469. else {
  91470. BABYLON.Tools.Warn("Function to remove was not found");
  91471. }
  91472. };
  91473. /**
  91474. * Register a function that will be executed after the physics step
  91475. */
  91476. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  91477. this._onAfterPhysicsStepCallbacks.push(func);
  91478. };
  91479. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  91480. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  91481. if (index > -1) {
  91482. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  91483. }
  91484. else {
  91485. BABYLON.Tools.Warn("Function to remove was not found");
  91486. }
  91487. };
  91488. /**
  91489. * register a function that will be executed when this impostor collides against a different body.
  91490. */
  91491. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  91492. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91493. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  91494. };
  91495. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  91496. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91497. var index = -1;
  91498. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  91499. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  91500. // chcek the arrays match
  91501. var sameList = cbDef.otherImpostors.every(function (impostor) {
  91502. return collidedAgainstList.indexOf(impostor) > -1;
  91503. });
  91504. if (sameList) {
  91505. index = idx;
  91506. }
  91507. return sameList;
  91508. }
  91509. return false;
  91510. });
  91511. if (found) {
  91512. this._onPhysicsCollideCallbacks.splice(index, 1);
  91513. }
  91514. else {
  91515. BABYLON.Tools.Warn("Function to remove was not found");
  91516. }
  91517. };
  91518. PhysicsImpostor.prototype.getParentsRotation = function () {
  91519. var parent = this.object.parent;
  91520. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  91521. while (parent) {
  91522. if (parent.rotationQuaternion) {
  91523. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  91524. }
  91525. else {
  91526. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  91527. }
  91528. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  91529. parent = parent.parent;
  91530. }
  91531. return this._tmpQuat;
  91532. };
  91533. /**
  91534. * Apply a force
  91535. */
  91536. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  91537. if (this._physicsEngine) {
  91538. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  91539. }
  91540. return this;
  91541. };
  91542. /**
  91543. * Apply an impulse
  91544. */
  91545. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  91546. if (this._physicsEngine) {
  91547. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  91548. }
  91549. return this;
  91550. };
  91551. /**
  91552. * A help function to create a joint.
  91553. */
  91554. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  91555. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  91556. this.addJoint(otherImpostor, joint);
  91557. return this;
  91558. };
  91559. /**
  91560. * Add a joint to this impostor with a different impostor.
  91561. */
  91562. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  91563. this._joints.push({
  91564. otherImpostor: otherImpostor,
  91565. joint: joint
  91566. });
  91567. if (this._physicsEngine) {
  91568. this._physicsEngine.addJoint(this, otherImpostor, joint);
  91569. }
  91570. return this;
  91571. };
  91572. /**
  91573. * Will keep this body still, in a sleep mode.
  91574. */
  91575. PhysicsImpostor.prototype.sleep = function () {
  91576. if (this._physicsEngine) {
  91577. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  91578. }
  91579. return this;
  91580. };
  91581. /**
  91582. * Wake the body up.
  91583. */
  91584. PhysicsImpostor.prototype.wakeUp = function () {
  91585. if (this._physicsEngine) {
  91586. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  91587. }
  91588. return this;
  91589. };
  91590. PhysicsImpostor.prototype.clone = function (newObject) {
  91591. if (!newObject)
  91592. return null;
  91593. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  91594. };
  91595. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  91596. var _this = this;
  91597. //no dispose if no physics engine is available.
  91598. if (!this._physicsEngine) {
  91599. return;
  91600. }
  91601. this._joints.forEach(function (j) {
  91602. if (_this._physicsEngine) {
  91603. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  91604. }
  91605. });
  91606. //dispose the physics body
  91607. this._physicsEngine.removeImpostor(this);
  91608. if (this.parent) {
  91609. this.parent.forceUpdate();
  91610. }
  91611. else {
  91612. /*this._object.getChildMeshes().forEach(function(mesh) {
  91613. if (mesh.physicsImpostor) {
  91614. if (disposeChildren) {
  91615. mesh.physicsImpostor.dispose();
  91616. mesh.physicsImpostor = null;
  91617. }
  91618. }
  91619. })*/
  91620. }
  91621. this._isDisposed = true;
  91622. };
  91623. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  91624. this._deltaPosition.copyFrom(position);
  91625. };
  91626. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  91627. if (!this._deltaRotation) {
  91628. this._deltaRotation = new BABYLON.Quaternion();
  91629. }
  91630. this._deltaRotation.copyFrom(rotation);
  91631. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  91632. };
  91633. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  91634. if (this._physicsEngine) {
  91635. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  91636. }
  91637. return this;
  91638. };
  91639. PhysicsImpostor.prototype.getRadius = function () {
  91640. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  91641. };
  91642. /**
  91643. * Sync a bone with this impostor
  91644. * @param bone The bone to sync to the impostor.
  91645. * @param boneMesh The mesh that the bone is influencing.
  91646. * @param jointPivot The pivot of the joint / bone in local space.
  91647. * @param distToJoint Optional distance from the impostor to the joint.
  91648. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91649. */
  91650. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  91651. var tempVec = PhysicsImpostor._tmpVecs[0];
  91652. var mesh = this.object;
  91653. if (mesh.rotationQuaternion) {
  91654. if (adjustRotation) {
  91655. var tempQuat = PhysicsImpostor._tmpQuat;
  91656. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  91657. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  91658. }
  91659. else {
  91660. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  91661. }
  91662. }
  91663. tempVec.x = 0;
  91664. tempVec.y = 0;
  91665. tempVec.z = 0;
  91666. if (jointPivot) {
  91667. tempVec.x = jointPivot.x;
  91668. tempVec.y = jointPivot.y;
  91669. tempVec.z = jointPivot.z;
  91670. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  91671. if (distToJoint === undefined || distToJoint === null) {
  91672. distToJoint = jointPivot.length();
  91673. }
  91674. tempVec.x *= distToJoint;
  91675. tempVec.y *= distToJoint;
  91676. tempVec.z *= distToJoint;
  91677. }
  91678. if (bone.getParent()) {
  91679. tempVec.addInPlace(mesh.getAbsolutePosition());
  91680. bone.setAbsolutePosition(tempVec, boneMesh);
  91681. }
  91682. else {
  91683. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  91684. boneMesh.position.x -= tempVec.x;
  91685. boneMesh.position.y -= tempVec.y;
  91686. boneMesh.position.z -= tempVec.z;
  91687. }
  91688. };
  91689. /**
  91690. * Sync impostor to a bone
  91691. * @param bone The bone that the impostor will be synced to.
  91692. * @param boneMesh The mesh that the bone is influencing.
  91693. * @param jointPivot The pivot of the joint / bone in local space.
  91694. * @param distToJoint Optional distance from the impostor to the joint.
  91695. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91696. * @param boneAxis Optional vector3 axis the bone is aligned with
  91697. */
  91698. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  91699. var mesh = this.object;
  91700. if (mesh.rotationQuaternion) {
  91701. if (adjustRotation) {
  91702. var tempQuat = PhysicsImpostor._tmpQuat;
  91703. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  91704. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  91705. }
  91706. else {
  91707. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  91708. }
  91709. }
  91710. var pos = PhysicsImpostor._tmpVecs[0];
  91711. var boneDir = PhysicsImpostor._tmpVecs[1];
  91712. if (!boneAxis) {
  91713. boneAxis = PhysicsImpostor._tmpVecs[2];
  91714. boneAxis.x = 0;
  91715. boneAxis.y = 1;
  91716. boneAxis.z = 0;
  91717. }
  91718. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  91719. bone.getAbsolutePositionToRef(boneMesh, pos);
  91720. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  91721. distToJoint = jointPivot.length();
  91722. }
  91723. if (distToJoint !== undefined && distToJoint !== null) {
  91724. pos.x += boneDir.x * distToJoint;
  91725. pos.y += boneDir.y * distToJoint;
  91726. pos.z += boneDir.z * distToJoint;
  91727. }
  91728. mesh.setAbsolutePosition(pos);
  91729. };
  91730. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  91731. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  91732. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91733. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  91734. //Impostor types
  91735. PhysicsImpostor.NoImpostor = 0;
  91736. PhysicsImpostor.SphereImpostor = 1;
  91737. PhysicsImpostor.BoxImpostor = 2;
  91738. PhysicsImpostor.PlaneImpostor = 3;
  91739. PhysicsImpostor.MeshImpostor = 4;
  91740. PhysicsImpostor.CylinderImpostor = 7;
  91741. PhysicsImpostor.ParticleImpostor = 8;
  91742. PhysicsImpostor.HeightmapImpostor = 9;
  91743. return PhysicsImpostor;
  91744. }());
  91745. BABYLON.PhysicsImpostor = PhysicsImpostor;
  91746. })(BABYLON || (BABYLON = {}));
  91747. //# sourceMappingURL=babylon.physicsImpostor.js.map
  91748. var BABYLON;
  91749. (function (BABYLON) {
  91750. /**
  91751. * Class used to control physics engine
  91752. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91753. */
  91754. var PhysicsEngine = /** @class */ (function () {
  91755. /**
  91756. * Creates a new Physics Engine
  91757. * @param gravity defines the gravity vector used by the simulation
  91758. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  91759. */
  91760. function PhysicsEngine(gravity, _physicsPlugin) {
  91761. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  91762. this._physicsPlugin = _physicsPlugin;
  91763. this._impostors = [];
  91764. this._joints = [];
  91765. if (!this._physicsPlugin.isSupported()) {
  91766. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  91767. + "Please make sure it is included.");
  91768. }
  91769. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  91770. this.setGravity(gravity);
  91771. this.setTimeStep();
  91772. }
  91773. /**
  91774. * Sets the gravity vector used by the simulation
  91775. * @param gravity defines the gravity vector to use
  91776. */
  91777. PhysicsEngine.prototype.setGravity = function (gravity) {
  91778. this.gravity = gravity;
  91779. this._physicsPlugin.setGravity(this.gravity);
  91780. };
  91781. /**
  91782. * Set the time step of the physics engine.
  91783. * Default is 1/60.
  91784. * To slow it down, enter 1/600 for example.
  91785. * To speed it up, 1/30
  91786. * @param newTimeStep defines the new timestep to apply to this world.
  91787. */
  91788. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  91789. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  91790. this._physicsPlugin.setTimeStep(newTimeStep);
  91791. };
  91792. /**
  91793. * Get the time step of the physics engine.
  91794. * @returns the current time step
  91795. */
  91796. PhysicsEngine.prototype.getTimeStep = function () {
  91797. return this._physicsPlugin.getTimeStep();
  91798. };
  91799. /**
  91800. * Release all resources
  91801. */
  91802. PhysicsEngine.prototype.dispose = function () {
  91803. this._impostors.forEach(function (impostor) {
  91804. impostor.dispose();
  91805. });
  91806. this._physicsPlugin.dispose();
  91807. };
  91808. /**
  91809. * Gets the name of the current physics plugin
  91810. * @returns the name of the plugin
  91811. */
  91812. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  91813. return this._physicsPlugin.name;
  91814. };
  91815. /**
  91816. * Adding a new impostor for the impostor tracking.
  91817. * This will be done by the impostor itself.
  91818. * @param impostor the impostor to add
  91819. */
  91820. PhysicsEngine.prototype.addImpostor = function (impostor) {
  91821. impostor.uniqueId = this._impostors.push(impostor);
  91822. //if no parent, generate the body
  91823. if (!impostor.parent) {
  91824. this._physicsPlugin.generatePhysicsBody(impostor);
  91825. }
  91826. };
  91827. /**
  91828. * Remove an impostor from the engine.
  91829. * This impostor and its mesh will not longer be updated by the physics engine.
  91830. * @param impostor the impostor to remove
  91831. */
  91832. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  91833. var index = this._impostors.indexOf(impostor);
  91834. if (index > -1) {
  91835. var removed = this._impostors.splice(index, 1);
  91836. //Is it needed?
  91837. if (removed.length) {
  91838. //this will also remove it from the world.
  91839. removed[0].physicsBody = null;
  91840. }
  91841. }
  91842. };
  91843. /**
  91844. * Add a joint to the physics engine
  91845. * @param mainImpostor defines the main impostor to which the joint is added.
  91846. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  91847. * @param joint defines the joint that will connect both impostors.
  91848. */
  91849. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  91850. var impostorJoint = {
  91851. mainImpostor: mainImpostor,
  91852. connectedImpostor: connectedImpostor,
  91853. joint: joint
  91854. };
  91855. joint.physicsPlugin = this._physicsPlugin;
  91856. this._joints.push(impostorJoint);
  91857. this._physicsPlugin.generateJoint(impostorJoint);
  91858. };
  91859. /**
  91860. * Removes a joint from the simulation
  91861. * @param mainImpostor defines the impostor used with the joint
  91862. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  91863. * @param joint defines the joint to remove
  91864. */
  91865. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  91866. var matchingJoints = this._joints.filter(function (impostorJoint) {
  91867. return (impostorJoint.connectedImpostor === connectedImpostor
  91868. && impostorJoint.joint === joint
  91869. && impostorJoint.mainImpostor === mainImpostor);
  91870. });
  91871. if (matchingJoints.length) {
  91872. this._physicsPlugin.removeJoint(matchingJoints[0]);
  91873. //TODO remove it from the list as well
  91874. }
  91875. };
  91876. /**
  91877. * Called by the scene. No need to call it.
  91878. * @param delta defines the timespam between frames
  91879. */
  91880. PhysicsEngine.prototype._step = function (delta) {
  91881. var _this = this;
  91882. //check if any mesh has no body / requires an update
  91883. this._impostors.forEach(function (impostor) {
  91884. if (impostor.isBodyInitRequired()) {
  91885. _this._physicsPlugin.generatePhysicsBody(impostor);
  91886. }
  91887. });
  91888. if (delta > 0.1) {
  91889. delta = 0.1;
  91890. }
  91891. else if (delta <= 0) {
  91892. delta = 1.0 / 60.0;
  91893. }
  91894. this._physicsPlugin.executeStep(delta, this._impostors);
  91895. };
  91896. /**
  91897. * Gets the current plugin used to run the simulation
  91898. * @returns current plugin
  91899. */
  91900. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  91901. return this._physicsPlugin;
  91902. };
  91903. /**
  91904. * Gets the list of physic impostors
  91905. * @returns an array of PhysicsImpostor
  91906. */
  91907. PhysicsEngine.prototype.getImpostors = function () {
  91908. return this._impostors;
  91909. };
  91910. /**
  91911. * Gets the impostor for a physics enabled object
  91912. * @param object defines the object impersonated by the impostor
  91913. * @returns the PhysicsImpostor or null if not found
  91914. */
  91915. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  91916. for (var i = 0; i < this._impostors.length; ++i) {
  91917. if (this._impostors[i].object === object) {
  91918. return this._impostors[i];
  91919. }
  91920. }
  91921. return null;
  91922. };
  91923. /**
  91924. * Gets the impostor for a physics body object
  91925. * @param body defines physics body used by the impostor
  91926. * @returns the PhysicsImpostor or null if not found
  91927. */
  91928. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  91929. for (var i = 0; i < this._impostors.length; ++i) {
  91930. if (this._impostors[i].physicsBody === body) {
  91931. return this._impostors[i];
  91932. }
  91933. }
  91934. return null;
  91935. };
  91936. /**
  91937. * Global value used to control the smallest number supported by the simulation
  91938. */
  91939. PhysicsEngine.Epsilon = 0.001;
  91940. return PhysicsEngine;
  91941. }());
  91942. BABYLON.PhysicsEngine = PhysicsEngine;
  91943. })(BABYLON || (BABYLON = {}));
  91944. //# sourceMappingURL=babylon.physicsEngine.js.map
  91945. var BABYLON;
  91946. (function (BABYLON) {
  91947. var PhysicsHelper = /** @class */ (function () {
  91948. function PhysicsHelper(scene) {
  91949. this._scene = scene;
  91950. this._physicsEngine = this._scene.getPhysicsEngine();
  91951. if (!this._physicsEngine) {
  91952. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  91953. }
  91954. }
  91955. /**
  91956. * @param {Vector3} origin the origin of the explosion
  91957. * @param {number} radius the explosion radius
  91958. * @param {number} strength the explosion strength
  91959. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91960. */
  91961. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  91962. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91963. if (!this._physicsEngine) {
  91964. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  91965. return null;
  91966. }
  91967. var impostors = this._physicsEngine.getImpostors();
  91968. if (impostors.length === 0) {
  91969. return null;
  91970. }
  91971. var event = new PhysicsRadialExplosionEvent(this._scene);
  91972. impostors.forEach(function (impostor) {
  91973. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91974. if (!impostorForceAndContactPoint) {
  91975. return;
  91976. }
  91977. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91978. });
  91979. event.dispose(false);
  91980. return event;
  91981. };
  91982. /**
  91983. * @param {Vector3} origin the origin of the explosion
  91984. * @param {number} radius the explosion radius
  91985. * @param {number} strength the explosion strength
  91986. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91987. */
  91988. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  91989. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91990. if (!this._physicsEngine) {
  91991. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91992. return null;
  91993. }
  91994. var impostors = this._physicsEngine.getImpostors();
  91995. if (impostors.length === 0) {
  91996. return null;
  91997. }
  91998. var event = new PhysicsRadialExplosionEvent(this._scene);
  91999. impostors.forEach(function (impostor) {
  92000. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92001. if (!impostorForceAndContactPoint) {
  92002. return;
  92003. }
  92004. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92005. });
  92006. event.dispose(false);
  92007. return event;
  92008. };
  92009. /**
  92010. * @param {Vector3} origin the origin of the explosion
  92011. * @param {number} radius the explosion radius
  92012. * @param {number} strength the explosion strength
  92013. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92014. */
  92015. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  92016. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92017. if (!this._physicsEngine) {
  92018. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92019. return null;
  92020. }
  92021. var impostors = this._physicsEngine.getImpostors();
  92022. if (impostors.length === 0) {
  92023. return null;
  92024. }
  92025. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  92026. event.dispose(false);
  92027. return event;
  92028. };
  92029. /**
  92030. * @param {Vector3} origin the origin of the updraft
  92031. * @param {number} radius the radius of the updraft
  92032. * @param {number} strength the strength of the updraft
  92033. * @param {number} height the height of the updraft
  92034. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  92035. */
  92036. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  92037. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  92038. if (!this._physicsEngine) {
  92039. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92040. return null;
  92041. }
  92042. if (this._physicsEngine.getImpostors().length === 0) {
  92043. return null;
  92044. }
  92045. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  92046. event.dispose(false);
  92047. return event;
  92048. };
  92049. /**
  92050. * @param {Vector3} origin the of the vortex
  92051. * @param {number} radius the radius of the vortex
  92052. * @param {number} strength the strength of the vortex
  92053. * @param {number} height the height of the vortex
  92054. */
  92055. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  92056. if (!this._physicsEngine) {
  92057. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92058. return null;
  92059. }
  92060. if (this._physicsEngine.getImpostors().length === 0) {
  92061. return null;
  92062. }
  92063. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  92064. event.dispose(false);
  92065. return event;
  92066. };
  92067. return PhysicsHelper;
  92068. }());
  92069. BABYLON.PhysicsHelper = PhysicsHelper;
  92070. /***** Radial explosion *****/
  92071. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  92072. function PhysicsRadialExplosionEvent(scene) {
  92073. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  92074. this._rays = [];
  92075. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  92076. this._scene = scene;
  92077. }
  92078. /**
  92079. * Returns the data related to the radial explosion event (sphere & rays).
  92080. * @returns {PhysicsRadialExplosionEventData}
  92081. */
  92082. PhysicsRadialExplosionEvent.prototype.getData = function () {
  92083. this._dataFetched = true;
  92084. return {
  92085. sphere: this._sphere,
  92086. rays: this._rays,
  92087. };
  92088. };
  92089. /**
  92090. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  92091. * @param impostor
  92092. * @param {Vector3} origin the origin of the explosion
  92093. * @param {number} radius the explosion radius
  92094. * @param {number} strength the explosion strength
  92095. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  92096. * @returns {Nullable<PhysicsForceAndContactPoint>}
  92097. */
  92098. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  92099. if (impostor.mass === 0) {
  92100. return null;
  92101. }
  92102. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  92103. return null;
  92104. }
  92105. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92106. return null;
  92107. }
  92108. var impostorObjectCenter = impostor.getObjectCenter();
  92109. var direction = impostorObjectCenter.subtract(origin);
  92110. var ray = new BABYLON.Ray(origin, direction, radius);
  92111. this._rays.push(ray);
  92112. var hit = ray.intersectsMesh(impostor.object);
  92113. var contactPoint = hit.pickedPoint;
  92114. if (!contactPoint) {
  92115. return null;
  92116. }
  92117. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  92118. if (distanceFromOrigin > radius) {
  92119. return null;
  92120. }
  92121. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  92122. ? strength
  92123. : strength * (1 - (distanceFromOrigin / radius));
  92124. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92125. return { force: force, contactPoint: contactPoint };
  92126. };
  92127. /**
  92128. * Disposes the sphere.
  92129. * @param {bolean} force
  92130. */
  92131. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  92132. var _this = this;
  92133. if (force === void 0) { force = true; }
  92134. if (force) {
  92135. this._sphere.dispose();
  92136. }
  92137. else {
  92138. setTimeout(function () {
  92139. if (!_this._dataFetched) {
  92140. _this._sphere.dispose();
  92141. }
  92142. }, 0);
  92143. }
  92144. };
  92145. /*** Helpers ***/
  92146. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  92147. if (!this._sphere) {
  92148. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  92149. this._sphere.isVisible = false;
  92150. }
  92151. };
  92152. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  92153. var impostorObject = impostor.object;
  92154. this._prepareSphere();
  92155. this._sphere.position = origin;
  92156. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  92157. this._sphere._updateBoundingInfo();
  92158. this._sphere.computeWorldMatrix(true);
  92159. return this._sphere.intersectsMesh(impostorObject, true);
  92160. };
  92161. return PhysicsRadialExplosionEvent;
  92162. }());
  92163. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  92164. /***** Gravitational Field *****/
  92165. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  92166. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  92167. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92168. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92169. this._physicsHelper = physicsHelper;
  92170. this._scene = scene;
  92171. this._origin = origin;
  92172. this._radius = radius;
  92173. this._strength = strength;
  92174. this._falloff = falloff;
  92175. this._tickCallback = this._tick.bind(this);
  92176. }
  92177. /**
  92178. * Returns the data related to the gravitational field event (sphere).
  92179. * @returns {PhysicsGravitationalFieldEventData}
  92180. */
  92181. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  92182. this._dataFetched = true;
  92183. return {
  92184. sphere: this._sphere,
  92185. };
  92186. };
  92187. /**
  92188. * Enables the gravitational field.
  92189. */
  92190. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  92191. this._tickCallback.call(this);
  92192. this._scene.registerBeforeRender(this._tickCallback);
  92193. };
  92194. /**
  92195. * Disables the gravitational field.
  92196. */
  92197. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  92198. this._scene.unregisterBeforeRender(this._tickCallback);
  92199. };
  92200. /**
  92201. * Disposes the sphere.
  92202. * @param {bolean} force
  92203. */
  92204. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  92205. var _this = this;
  92206. if (force === void 0) { force = true; }
  92207. if (force) {
  92208. this._sphere.dispose();
  92209. }
  92210. else {
  92211. setTimeout(function () {
  92212. if (!_this._dataFetched) {
  92213. _this._sphere.dispose();
  92214. }
  92215. }, 0);
  92216. }
  92217. };
  92218. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  92219. // Since the params won't change, we fetch the event only once
  92220. if (this._sphere) {
  92221. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92222. }
  92223. else {
  92224. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92225. if (radialExplosionEvent) {
  92226. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  92227. }
  92228. }
  92229. };
  92230. return PhysicsGravitationalFieldEvent;
  92231. }());
  92232. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  92233. /***** Updraft *****/
  92234. var PhysicsUpdraftEvent = /** @class */ (function () {
  92235. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  92236. this._scene = _scene;
  92237. this._origin = _origin;
  92238. this._radius = _radius;
  92239. this._strength = _strength;
  92240. this._height = _height;
  92241. this._updraftMode = _updraftMode;
  92242. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92243. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  92244. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92245. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92246. this._physicsEngine = this._scene.getPhysicsEngine();
  92247. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92248. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92249. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92250. this._originDirection = this._origin.subtract(this._originTop).normalize();
  92251. }
  92252. this._tickCallback = this._tick.bind(this);
  92253. }
  92254. /**
  92255. * Returns the data related to the updraft event (cylinder).
  92256. * @returns {PhysicsUpdraftEventData}
  92257. */
  92258. PhysicsUpdraftEvent.prototype.getData = function () {
  92259. this._dataFetched = true;
  92260. return {
  92261. cylinder: this._cylinder,
  92262. };
  92263. };
  92264. /**
  92265. * Enables the updraft.
  92266. */
  92267. PhysicsUpdraftEvent.prototype.enable = function () {
  92268. this._tickCallback.call(this);
  92269. this._scene.registerBeforeRender(this._tickCallback);
  92270. };
  92271. /**
  92272. * Disables the cortex.
  92273. */
  92274. PhysicsUpdraftEvent.prototype.disable = function () {
  92275. this._scene.unregisterBeforeRender(this._tickCallback);
  92276. };
  92277. /**
  92278. * Disposes the sphere.
  92279. * @param {bolean} force
  92280. */
  92281. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  92282. var _this = this;
  92283. if (force === void 0) { force = true; }
  92284. if (force) {
  92285. this._cylinder.dispose();
  92286. }
  92287. else {
  92288. setTimeout(function () {
  92289. if (!_this._dataFetched) {
  92290. _this._cylinder.dispose();
  92291. }
  92292. }, 0);
  92293. }
  92294. };
  92295. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92296. if (impostor.mass === 0) {
  92297. return null;
  92298. }
  92299. if (!this._intersectsWithCylinder(impostor)) {
  92300. return null;
  92301. }
  92302. var impostorObjectCenter = impostor.getObjectCenter();
  92303. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92304. var direction = this._originDirection;
  92305. }
  92306. else {
  92307. var direction = impostorObjectCenter.subtract(this._originTop);
  92308. }
  92309. var multiplier = this._strength * -1;
  92310. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92311. return { force: force, contactPoint: impostorObjectCenter };
  92312. };
  92313. PhysicsUpdraftEvent.prototype._tick = function () {
  92314. var _this = this;
  92315. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92316. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92317. if (!impostorForceAndContactPoint) {
  92318. return;
  92319. }
  92320. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92321. });
  92322. };
  92323. /*** Helpers ***/
  92324. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  92325. if (!this._cylinder) {
  92326. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  92327. height: this._height,
  92328. diameter: this._radius * 2,
  92329. }, this._scene);
  92330. this._cylinder.isVisible = false;
  92331. }
  92332. };
  92333. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  92334. var impostorObject = impostor.object;
  92335. this._prepareCylinder();
  92336. this._cylinder.position = this._cylinderPosition;
  92337. return this._cylinder.intersectsMesh(impostorObject, true);
  92338. };
  92339. return PhysicsUpdraftEvent;
  92340. }());
  92341. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  92342. /***** Vortex *****/
  92343. var PhysicsVortexEvent = /** @class */ (function () {
  92344. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  92345. this._scene = _scene;
  92346. this._origin = _origin;
  92347. this._radius = _radius;
  92348. this._strength = _strength;
  92349. this._height = _height;
  92350. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92351. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  92352. this._updraftMultiplier = 0.02;
  92353. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92354. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92355. this._physicsEngine = this._scene.getPhysicsEngine();
  92356. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92357. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92358. this._tickCallback = this._tick.bind(this);
  92359. }
  92360. /**
  92361. * Returns the data related to the vortex event (cylinder).
  92362. * @returns {PhysicsVortexEventData}
  92363. */
  92364. PhysicsVortexEvent.prototype.getData = function () {
  92365. this._dataFetched = true;
  92366. return {
  92367. cylinder: this._cylinder,
  92368. };
  92369. };
  92370. /**
  92371. * Enables the vortex.
  92372. */
  92373. PhysicsVortexEvent.prototype.enable = function () {
  92374. this._tickCallback.call(this);
  92375. this._scene.registerBeforeRender(this._tickCallback);
  92376. };
  92377. /**
  92378. * Disables the cortex.
  92379. */
  92380. PhysicsVortexEvent.prototype.disable = function () {
  92381. this._scene.unregisterBeforeRender(this._tickCallback);
  92382. };
  92383. /**
  92384. * Disposes the sphere.
  92385. * @param {bolean} force
  92386. */
  92387. PhysicsVortexEvent.prototype.dispose = function (force) {
  92388. var _this = this;
  92389. if (force === void 0) { force = true; }
  92390. if (force) {
  92391. this._cylinder.dispose();
  92392. }
  92393. else {
  92394. setTimeout(function () {
  92395. if (!_this._dataFetched) {
  92396. _this._cylinder.dispose();
  92397. }
  92398. }, 0);
  92399. }
  92400. };
  92401. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92402. if (impostor.mass === 0) {
  92403. return null;
  92404. }
  92405. if (!this._intersectsWithCylinder(impostor)) {
  92406. return null;
  92407. }
  92408. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92409. return null;
  92410. }
  92411. var impostorObjectCenter = impostor.getObjectCenter();
  92412. 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)
  92413. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  92414. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  92415. var hit = ray.intersectsMesh(impostor.object);
  92416. var contactPoint = hit.pickedPoint;
  92417. if (!contactPoint) {
  92418. return null;
  92419. }
  92420. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  92421. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  92422. var directionToOrigin = contactPoint.normalize();
  92423. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92424. directionToOrigin = directionToOrigin.negate();
  92425. }
  92426. // TODO: find a more physically based solution
  92427. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92428. var forceX = directionToOrigin.x * this._strength / 8;
  92429. var forceY = directionToOrigin.y * this._updraftMultiplier;
  92430. var forceZ = directionToOrigin.z * this._strength / 8;
  92431. }
  92432. else {
  92433. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  92434. var forceY = this._originTop.y * this._updraftMultiplier;
  92435. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  92436. }
  92437. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  92438. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  92439. return { force: force, contactPoint: impostorObjectCenter };
  92440. };
  92441. PhysicsVortexEvent.prototype._tick = function () {
  92442. var _this = this;
  92443. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92444. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92445. if (!impostorForceAndContactPoint) {
  92446. return;
  92447. }
  92448. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92449. });
  92450. };
  92451. /*** Helpers ***/
  92452. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  92453. if (!this._cylinder) {
  92454. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  92455. height: this._height,
  92456. diameter: this._radius * 2,
  92457. }, this._scene);
  92458. this._cylinder.isVisible = false;
  92459. }
  92460. };
  92461. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  92462. var impostorObject = impostor.object;
  92463. this._prepareCylinder();
  92464. this._cylinder.position = this._cylinderPosition;
  92465. return this._cylinder.intersectsMesh(impostorObject, true);
  92466. };
  92467. return PhysicsVortexEvent;
  92468. }());
  92469. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  92470. /***** Enums *****/
  92471. /**
  92472. * The strenght of the force in correspondence to the distance of the affected object
  92473. */
  92474. var PhysicsRadialImpulseFalloff;
  92475. (function (PhysicsRadialImpulseFalloff) {
  92476. /** Defines that impulse is constant in strength across it's whole radius */
  92477. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  92478. /** DEfines that impulse gets weaker if it's further from the origin */
  92479. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  92480. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  92481. /**
  92482. * The strenght of the force in correspondence to the distance of the affected object
  92483. */
  92484. var PhysicsUpdraftMode;
  92485. (function (PhysicsUpdraftMode) {
  92486. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  92487. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  92488. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  92489. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  92490. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  92491. })(BABYLON || (BABYLON = {}));
  92492. //# sourceMappingURL=babylon.physicsHelper.js.map
  92493. var BABYLON;
  92494. (function (BABYLON) {
  92495. /** @hidden */
  92496. var CannonJSPlugin = /** @class */ (function () {
  92497. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  92498. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  92499. if (iterations === void 0) { iterations = 10; }
  92500. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  92501. this.name = "CannonJSPlugin";
  92502. this._physicsMaterials = new Array();
  92503. this._fixedTimeStep = 1 / 60;
  92504. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  92505. this.BJSCANNON = CANNON;
  92506. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  92507. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  92508. this._tmpPosition = BABYLON.Vector3.Zero();
  92509. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  92510. this._tmpUnityRotation = new BABYLON.Quaternion();
  92511. if (!this.isSupported()) {
  92512. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  92513. return;
  92514. }
  92515. this._extendNamespace();
  92516. this.world = new this.BJSCANNON.World();
  92517. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  92518. this.world.solver.iterations = iterations;
  92519. }
  92520. CannonJSPlugin.prototype.setGravity = function (gravity) {
  92521. this.world.gravity.copy(gravity);
  92522. };
  92523. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  92524. this._fixedTimeStep = timeStep;
  92525. };
  92526. CannonJSPlugin.prototype.getTimeStep = function () {
  92527. return this._fixedTimeStep;
  92528. };
  92529. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  92530. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  92531. };
  92532. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92533. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92534. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92535. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  92536. };
  92537. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92538. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92539. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92540. impostor.physicsBody.applyForce(impulse, worldPoint);
  92541. };
  92542. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92543. //parent-child relationship. Does this impostor has a parent impostor?
  92544. if (impostor.parent) {
  92545. if (impostor.physicsBody) {
  92546. this.removePhysicsBody(impostor);
  92547. //TODO is that needed?
  92548. impostor.forceUpdate();
  92549. }
  92550. return;
  92551. }
  92552. //should a new body be created for this impostor?
  92553. if (impostor.isBodyInitRequired()) {
  92554. var shape = this._createShape(impostor);
  92555. //unregister events, if body is being changed
  92556. var oldBody = impostor.physicsBody;
  92557. if (oldBody) {
  92558. this.removePhysicsBody(impostor);
  92559. }
  92560. //create the body and material
  92561. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  92562. var bodyCreationObject = {
  92563. mass: impostor.getParam("mass"),
  92564. material: material
  92565. };
  92566. // A simple extend, in case native options were used.
  92567. var nativeOptions = impostor.getParam("nativeOptions");
  92568. for (var key in nativeOptions) {
  92569. if (nativeOptions.hasOwnProperty(key)) {
  92570. bodyCreationObject[key] = nativeOptions[key];
  92571. }
  92572. }
  92573. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  92574. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  92575. this.world.addEventListener("preStep", impostor.beforeStep);
  92576. this.world.addEventListener("postStep", impostor.afterStep);
  92577. impostor.physicsBody.addShape(shape);
  92578. this.world.add(impostor.physicsBody);
  92579. //try to keep the body moving in the right direction by taking old properties.
  92580. //Should be tested!
  92581. if (oldBody) {
  92582. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  92583. impostor.physicsBody[param].copy(oldBody[param]);
  92584. });
  92585. }
  92586. this._processChildMeshes(impostor);
  92587. }
  92588. //now update the body's transformation
  92589. this._updatePhysicsBodyTransformation(impostor);
  92590. };
  92591. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  92592. var _this = this;
  92593. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  92594. var currentRotation = mainImpostor.object.rotationQuaternion;
  92595. if (meshChildren.length) {
  92596. var processMesh = function (localPosition, mesh) {
  92597. if (!currentRotation || !mesh.rotationQuaternion) {
  92598. return;
  92599. }
  92600. var childImpostor = mesh.getPhysicsImpostor();
  92601. if (childImpostor) {
  92602. var parent = childImpostor.parent;
  92603. if (parent !== mainImpostor) {
  92604. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  92605. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  92606. if (childImpostor.physicsBody) {
  92607. _this.removePhysicsBody(childImpostor);
  92608. childImpostor.physicsBody = null;
  92609. }
  92610. childImpostor.parent = mainImpostor;
  92611. childImpostor.resetUpdateFlags();
  92612. 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));
  92613. //Add the mass of the children.
  92614. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  92615. }
  92616. }
  92617. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  92618. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  92619. };
  92620. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  92621. }
  92622. };
  92623. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92624. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  92625. this.world.removeEventListener("preStep", impostor.beforeStep);
  92626. this.world.removeEventListener("postStep", impostor.afterStep);
  92627. this.world.remove(impostor.physicsBody);
  92628. };
  92629. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92630. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92631. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92632. if (!mainBody || !connectedBody) {
  92633. return;
  92634. }
  92635. var constraint;
  92636. var jointData = impostorJoint.joint.jointData;
  92637. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  92638. var constraintData = {
  92639. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  92640. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  92641. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  92642. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  92643. maxForce: jointData.nativeParams.maxForce,
  92644. collideConnected: !!jointData.collision
  92645. };
  92646. switch (impostorJoint.joint.type) {
  92647. case BABYLON.PhysicsJoint.HingeJoint:
  92648. case BABYLON.PhysicsJoint.Hinge2Joint:
  92649. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  92650. break;
  92651. case BABYLON.PhysicsJoint.DistanceJoint:
  92652. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  92653. break;
  92654. case BABYLON.PhysicsJoint.SpringJoint:
  92655. var springData = jointData;
  92656. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  92657. restLength: springData.length,
  92658. stiffness: springData.stiffness,
  92659. damping: springData.damping,
  92660. localAnchorA: constraintData.pivotA,
  92661. localAnchorB: constraintData.pivotB
  92662. });
  92663. break;
  92664. case BABYLON.PhysicsJoint.LockJoint:
  92665. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  92666. break;
  92667. case BABYLON.PhysicsJoint.PointToPointJoint:
  92668. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92669. default:
  92670. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  92671. break;
  92672. }
  92673. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  92674. constraint.collideConnected = !!jointData.collision;
  92675. impostorJoint.joint.physicsJoint = constraint;
  92676. //don't add spring as constraint, as it is not one.
  92677. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92678. this.world.addConstraint(constraint);
  92679. }
  92680. else {
  92681. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  92682. constraint.applyForce();
  92683. };
  92684. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92685. }
  92686. };
  92687. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92688. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92689. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  92690. }
  92691. else {
  92692. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92693. }
  92694. };
  92695. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  92696. var index;
  92697. var mat;
  92698. for (index = 0; index < this._physicsMaterials.length; index++) {
  92699. mat = this._physicsMaterials[index];
  92700. if (mat.friction === friction && mat.restitution === restitution) {
  92701. return mat;
  92702. }
  92703. }
  92704. var currentMat = new this.BJSCANNON.Material(name);
  92705. currentMat.friction = friction;
  92706. currentMat.restitution = restitution;
  92707. this._physicsMaterials.push(currentMat);
  92708. return currentMat;
  92709. };
  92710. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  92711. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  92712. };
  92713. CannonJSPlugin.prototype._createShape = function (impostor) {
  92714. var object = impostor.object;
  92715. var returnValue;
  92716. var extendSize = impostor.getObjectExtendSize();
  92717. switch (impostor.type) {
  92718. case BABYLON.PhysicsImpostor.SphereImpostor:
  92719. var radiusX = extendSize.x;
  92720. var radiusY = extendSize.y;
  92721. var radiusZ = extendSize.z;
  92722. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  92723. break;
  92724. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  92725. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92726. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  92727. break;
  92728. case BABYLON.PhysicsImpostor.BoxImpostor:
  92729. var box = extendSize.scale(0.5);
  92730. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  92731. break;
  92732. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92733. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  92734. returnValue = new this.BJSCANNON.Plane();
  92735. break;
  92736. case BABYLON.PhysicsImpostor.MeshImpostor:
  92737. // should transform the vertex data to world coordinates!!
  92738. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  92739. var rawFaces = object.getIndices ? object.getIndices() : [];
  92740. if (!rawVerts)
  92741. return;
  92742. // get only scale! so the object could transform correctly.
  92743. var oldPosition = object.position.clone();
  92744. var oldRotation = object.rotation && object.rotation.clone();
  92745. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  92746. object.position.copyFromFloats(0, 0, 0);
  92747. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92748. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92749. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92750. var transform = object.computeWorldMatrix(true);
  92751. // convert rawVerts to object space
  92752. var temp = new Array();
  92753. var index;
  92754. for (index = 0; index < rawVerts.length; index += 3) {
  92755. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  92756. }
  92757. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  92758. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  92759. //now set back the transformation!
  92760. object.position.copyFrom(oldPosition);
  92761. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  92762. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  92763. break;
  92764. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  92765. var oldPosition2 = object.position.clone();
  92766. var oldRotation2 = object.rotation && object.rotation.clone();
  92767. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  92768. object.position.copyFromFloats(0, 0, 0);
  92769. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92770. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92771. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92772. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  92773. returnValue = this._createHeightmap(object);
  92774. object.position.copyFrom(oldPosition2);
  92775. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  92776. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  92777. object.computeWorldMatrix(true);
  92778. break;
  92779. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92780. returnValue = new this.BJSCANNON.Particle();
  92781. break;
  92782. }
  92783. return returnValue;
  92784. };
  92785. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  92786. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92787. var transform = object.computeWorldMatrix(true);
  92788. // convert rawVerts to object space
  92789. var temp = new Array();
  92790. var index;
  92791. for (index = 0; index < pos.length; index += 3) {
  92792. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  92793. }
  92794. pos = temp;
  92795. var matrix = new Array();
  92796. //For now pointDepth will not be used and will be automatically calculated.
  92797. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  92798. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  92799. var boundingInfo = object.getBoundingInfo();
  92800. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  92801. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  92802. var elementSize = dim * 2 / arraySize;
  92803. for (var i = 0; i < pos.length; i = i + 3) {
  92804. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  92805. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  92806. var y = -pos[i + 2] + minY;
  92807. if (!matrix[x]) {
  92808. matrix[x] = [];
  92809. }
  92810. if (!matrix[x][z]) {
  92811. matrix[x][z] = y;
  92812. }
  92813. matrix[x][z] = Math.max(y, matrix[x][z]);
  92814. }
  92815. for (var x = 0; x <= arraySize; ++x) {
  92816. if (!matrix[x]) {
  92817. var loc = 1;
  92818. while (!matrix[(x + loc) % arraySize]) {
  92819. loc++;
  92820. }
  92821. matrix[x] = matrix[(x + loc) % arraySize].slice();
  92822. //console.log("missing x", x);
  92823. }
  92824. for (var z = 0; z <= arraySize; ++z) {
  92825. if (!matrix[x][z]) {
  92826. var loc = 1;
  92827. var newValue;
  92828. while (newValue === undefined) {
  92829. newValue = matrix[x][(z + loc++) % arraySize];
  92830. }
  92831. matrix[x][z] = newValue;
  92832. }
  92833. }
  92834. }
  92835. var shape = new this.BJSCANNON.Heightfield(matrix, {
  92836. elementSize: elementSize
  92837. });
  92838. //For future reference, needed for body transformation
  92839. shape.minY = minY;
  92840. return shape;
  92841. };
  92842. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  92843. var object = impostor.object;
  92844. //make sure it is updated...
  92845. object.computeWorldMatrix && object.computeWorldMatrix(true);
  92846. // The delta between the mesh position and the mesh bounding box center
  92847. var bInfo = object.getBoundingInfo();
  92848. if (!bInfo)
  92849. return;
  92850. var center = impostor.getObjectCenter();
  92851. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  92852. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  92853. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  92854. this._tmpPosition.copyFrom(center);
  92855. var quaternion = object.rotationQuaternion;
  92856. if (!quaternion) {
  92857. return;
  92858. }
  92859. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  92860. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  92861. //-90 DEG in X, precalculated
  92862. quaternion = quaternion.multiply(this._minus90X);
  92863. //Invert! (Precalculated, 90 deg in X)
  92864. //No need to clone. this will never change.
  92865. impostor.setDeltaRotation(this._plus90X);
  92866. }
  92867. //If it is a heightfield, if should be centered.
  92868. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  92869. var mesh = object;
  92870. var boundingInfo = mesh.getBoundingInfo();
  92871. //calculate the correct body position:
  92872. var rotationQuaternion = mesh.rotationQuaternion;
  92873. mesh.rotationQuaternion = this._tmpUnityRotation;
  92874. mesh.computeWorldMatrix(true);
  92875. //get original center with no rotation
  92876. var c = center.clone();
  92877. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  92878. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  92879. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  92880. mesh.setPreTransformMatrix(p);
  92881. mesh.computeWorldMatrix(true);
  92882. //calculate the translation
  92883. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  92884. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  92885. //add it inverted to the delta
  92886. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  92887. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  92888. //rotation is back
  92889. mesh.rotationQuaternion = rotationQuaternion;
  92890. mesh.setPreTransformMatrix(oldPivot);
  92891. mesh.computeWorldMatrix(true);
  92892. }
  92893. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  92894. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  92895. //this._tmpPosition.copyFrom(object.position);
  92896. }
  92897. impostor.setDeltaPosition(this._tmpDeltaPosition);
  92898. //Now update the impostor object
  92899. impostor.physicsBody.position.copy(this._tmpPosition);
  92900. impostor.physicsBody.quaternion.copy(quaternion);
  92901. };
  92902. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92903. impostor.object.position.copyFrom(impostor.physicsBody.position);
  92904. if (impostor.object.rotationQuaternion) {
  92905. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  92906. }
  92907. };
  92908. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92909. impostor.physicsBody.position.copy(newPosition);
  92910. impostor.physicsBody.quaternion.copy(newRotation);
  92911. };
  92912. CannonJSPlugin.prototype.isSupported = function () {
  92913. return this.BJSCANNON !== undefined;
  92914. };
  92915. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92916. impostor.physicsBody.velocity.copy(velocity);
  92917. };
  92918. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92919. impostor.physicsBody.angularVelocity.copy(velocity);
  92920. };
  92921. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92922. var v = impostor.physicsBody.velocity;
  92923. if (!v) {
  92924. return null;
  92925. }
  92926. return new BABYLON.Vector3(v.x, v.y, v.z);
  92927. };
  92928. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92929. var v = impostor.physicsBody.angularVelocity;
  92930. if (!v) {
  92931. return null;
  92932. }
  92933. return new BABYLON.Vector3(v.x, v.y, v.z);
  92934. };
  92935. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92936. impostor.physicsBody.mass = mass;
  92937. impostor.physicsBody.updateMassProperties();
  92938. };
  92939. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  92940. return impostor.physicsBody.mass;
  92941. };
  92942. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  92943. return impostor.physicsBody.material.friction;
  92944. };
  92945. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92946. impostor.physicsBody.material.friction = friction;
  92947. };
  92948. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92949. return impostor.physicsBody.material.restitution;
  92950. };
  92951. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92952. impostor.physicsBody.material.restitution = restitution;
  92953. };
  92954. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  92955. impostor.physicsBody.sleep();
  92956. };
  92957. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  92958. impostor.physicsBody.wakeUp();
  92959. };
  92960. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92961. joint.physicsJoint.distance = maxDistance;
  92962. };
  92963. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92964. // if (!motorIndex) {
  92965. // joint.physicsJoint.enableMotor();
  92966. // }
  92967. // }
  92968. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92969. // if (!motorIndex) {
  92970. // joint.physicsJoint.disableMotor();
  92971. // }
  92972. // }
  92973. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92974. if (!motorIndex) {
  92975. joint.physicsJoint.enableMotor();
  92976. joint.physicsJoint.setMotorSpeed(speed);
  92977. if (maxForce) {
  92978. this.setLimit(joint, maxForce);
  92979. }
  92980. }
  92981. };
  92982. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  92983. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  92984. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  92985. };
  92986. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92987. var body = impostor.physicsBody;
  92988. mesh.position.x = body.position.x;
  92989. mesh.position.y = body.position.y;
  92990. mesh.position.z = body.position.z;
  92991. if (mesh.rotationQuaternion) {
  92992. mesh.rotationQuaternion.x = body.quaternion.x;
  92993. mesh.rotationQuaternion.y = body.quaternion.y;
  92994. mesh.rotationQuaternion.z = body.quaternion.z;
  92995. mesh.rotationQuaternion.w = body.quaternion.w;
  92996. }
  92997. };
  92998. CannonJSPlugin.prototype.getRadius = function (impostor) {
  92999. var shape = impostor.physicsBody.shapes[0];
  93000. return shape.boundingSphereRadius;
  93001. };
  93002. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93003. var shape = impostor.physicsBody.shapes[0];
  93004. result.x = shape.halfExtents.x * 2;
  93005. result.y = shape.halfExtents.y * 2;
  93006. result.z = shape.halfExtents.z * 2;
  93007. };
  93008. CannonJSPlugin.prototype.dispose = function () {
  93009. };
  93010. CannonJSPlugin.prototype._extendNamespace = function () {
  93011. //this will force cannon to execute at least one step when using interpolation
  93012. var step_tmp1 = new this.BJSCANNON.Vec3();
  93013. var Engine = this.BJSCANNON;
  93014. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  93015. maxSubSteps = maxSubSteps || 10;
  93016. timeSinceLastCalled = timeSinceLastCalled || 0;
  93017. if (timeSinceLastCalled === 0) {
  93018. this.internalStep(dt);
  93019. this.time += dt;
  93020. }
  93021. else {
  93022. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  93023. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  93024. var t0 = performance.now();
  93025. for (var i = 0; i !== internalSteps; i++) {
  93026. this.internalStep(dt);
  93027. if (performance.now() - t0 > dt * 1000) {
  93028. break;
  93029. }
  93030. }
  93031. this.time += timeSinceLastCalled;
  93032. var h = this.time % dt;
  93033. var h_div_dt = h / dt;
  93034. var interpvelo = step_tmp1;
  93035. var bodies = this.bodies;
  93036. for (var j = 0; j !== bodies.length; j++) {
  93037. var b = bodies[j];
  93038. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  93039. b.position.vsub(b.previousPosition, interpvelo);
  93040. interpvelo.scale(h_div_dt, interpvelo);
  93041. b.position.vadd(interpvelo, b.interpolatedPosition);
  93042. }
  93043. else {
  93044. b.interpolatedPosition.copy(b.position);
  93045. b.interpolatedQuaternion.copy(b.quaternion);
  93046. }
  93047. }
  93048. }
  93049. };
  93050. };
  93051. return CannonJSPlugin;
  93052. }());
  93053. BABYLON.CannonJSPlugin = CannonJSPlugin;
  93054. })(BABYLON || (BABYLON = {}));
  93055. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  93056. var BABYLON;
  93057. (function (BABYLON) {
  93058. /** @hidden */
  93059. var OimoJSPlugin = /** @class */ (function () {
  93060. function OimoJSPlugin(iterations) {
  93061. this.name = "OimoJSPlugin";
  93062. this._tmpImpostorsArray = [];
  93063. this._tmpPositionVector = BABYLON.Vector3.Zero();
  93064. this.BJSOIMO = OIMO;
  93065. this.world = new this.BJSOIMO.World({
  93066. iterations: iterations
  93067. });
  93068. this.world.clear();
  93069. }
  93070. OimoJSPlugin.prototype.setGravity = function (gravity) {
  93071. this.world.gravity.copy(gravity);
  93072. };
  93073. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  93074. this.world.timeStep = timeStep;
  93075. };
  93076. OimoJSPlugin.prototype.getTimeStep = function () {
  93077. return this.world.timeStep;
  93078. };
  93079. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  93080. var _this = this;
  93081. impostors.forEach(function (impostor) {
  93082. impostor.beforeStep();
  93083. });
  93084. this.world.step();
  93085. impostors.forEach(function (impostor) {
  93086. impostor.afterStep();
  93087. //update the ordered impostors array
  93088. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  93089. });
  93090. //check for collisions
  93091. var contact = this.world.contacts;
  93092. while (contact !== null) {
  93093. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  93094. contact = contact.next;
  93095. continue;
  93096. }
  93097. //is this body colliding with any other? get the impostor
  93098. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  93099. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  93100. if (!mainImpostor || !collidingImpostor) {
  93101. contact = contact.next;
  93102. continue;
  93103. }
  93104. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  93105. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  93106. contact = contact.next;
  93107. }
  93108. };
  93109. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93110. var mass = impostor.physicsBody.mass;
  93111. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  93112. };
  93113. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93114. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  93115. this.applyImpulse(impostor, force, contactPoint);
  93116. };
  93117. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93118. var _this = this;
  93119. //parent-child relationship. Does this impostor has a parent impostor?
  93120. if (impostor.parent) {
  93121. if (impostor.physicsBody) {
  93122. this.removePhysicsBody(impostor);
  93123. //TODO is that needed?
  93124. impostor.forceUpdate();
  93125. }
  93126. return;
  93127. }
  93128. if (impostor.isBodyInitRequired()) {
  93129. var bodyConfig = {
  93130. name: impostor.uniqueId,
  93131. //Oimo must have mass, also for static objects.
  93132. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  93133. size: [],
  93134. type: [],
  93135. pos: [],
  93136. posShape: [],
  93137. rot: [],
  93138. rotShape: [],
  93139. move: impostor.getParam("mass") !== 0,
  93140. density: impostor.getParam("mass"),
  93141. friction: impostor.getParam("friction"),
  93142. restitution: impostor.getParam("restitution"),
  93143. //Supporting older versions of Oimo
  93144. world: this.world
  93145. };
  93146. var impostors = [impostor];
  93147. var addToArray = function (parent) {
  93148. if (!parent.getChildMeshes)
  93149. return;
  93150. parent.getChildMeshes().forEach(function (m) {
  93151. if (m.physicsImpostor) {
  93152. impostors.push(m.physicsImpostor);
  93153. //m.physicsImpostor._init();
  93154. }
  93155. });
  93156. };
  93157. addToArray(impostor.object);
  93158. var checkWithEpsilon_1 = function (value) {
  93159. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  93160. };
  93161. var globalQuaternion_1 = new BABYLON.Quaternion();
  93162. impostors.forEach(function (i) {
  93163. if (!i.object.rotationQuaternion) {
  93164. return;
  93165. }
  93166. //get the correct bounding box
  93167. var oldQuaternion = i.object.rotationQuaternion;
  93168. globalQuaternion_1 = oldQuaternion.clone();
  93169. var rot = oldQuaternion.toEulerAngles();
  93170. var extendSize = i.getObjectExtendSize();
  93171. var radToDeg = 57.295779513082320876;
  93172. if (i === impostor) {
  93173. var center = impostor.getObjectCenter();
  93174. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  93175. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  93176. //Can also use Array.prototype.push.apply
  93177. bodyConfig.pos.push(center.x);
  93178. bodyConfig.pos.push(center.y);
  93179. bodyConfig.pos.push(center.z);
  93180. bodyConfig.posShape.push(0, 0, 0);
  93181. //tmp solution
  93182. bodyConfig.rot.push(0);
  93183. bodyConfig.rot.push(0);
  93184. bodyConfig.rot.push(0);
  93185. bodyConfig.rotShape.push(0, 0, 0);
  93186. }
  93187. else {
  93188. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  93189. bodyConfig.posShape.push(localPosition.x);
  93190. bodyConfig.posShape.push(localPosition.y);
  93191. bodyConfig.posShape.push(localPosition.z);
  93192. bodyConfig.pos.push(0, 0, 0);
  93193. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  93194. bodyConfig.rot.push(0);
  93195. bodyConfig.rot.push(0);
  93196. bodyConfig.rot.push(0);
  93197. bodyConfig.rotShape.push(rot.x * radToDeg);
  93198. bodyConfig.rotShape.push(rot.y * radToDeg);
  93199. bodyConfig.rotShape.push(rot.z * radToDeg);
  93200. }
  93201. // register mesh
  93202. switch (i.type) {
  93203. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93204. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  93205. case BABYLON.PhysicsImpostor.SphereImpostor:
  93206. var radiusX = extendSize.x;
  93207. var radiusY = extendSize.y;
  93208. var radiusZ = extendSize.z;
  93209. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  93210. bodyConfig.type.push('sphere');
  93211. //due to the way oimo works with compounds, add 3 times
  93212. bodyConfig.size.push(size);
  93213. bodyConfig.size.push(size);
  93214. bodyConfig.size.push(size);
  93215. break;
  93216. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93217. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  93218. var sizeY = checkWithEpsilon_1(extendSize.y);
  93219. bodyConfig.type.push('cylinder');
  93220. bodyConfig.size.push(sizeX);
  93221. bodyConfig.size.push(sizeY);
  93222. //due to the way oimo works with compounds, add one more value.
  93223. bodyConfig.size.push(sizeY);
  93224. break;
  93225. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93226. case BABYLON.PhysicsImpostor.BoxImpostor:
  93227. default:
  93228. var sizeX = checkWithEpsilon_1(extendSize.x);
  93229. var sizeY = checkWithEpsilon_1(extendSize.y);
  93230. var sizeZ = checkWithEpsilon_1(extendSize.z);
  93231. bodyConfig.type.push('box');
  93232. //if (i === impostor) {
  93233. bodyConfig.size.push(sizeX);
  93234. bodyConfig.size.push(sizeY);
  93235. bodyConfig.size.push(sizeZ);
  93236. //} else {
  93237. // bodyConfig.size.push(0,0,0);
  93238. //}
  93239. break;
  93240. }
  93241. //actually not needed, but hey...
  93242. i.object.rotationQuaternion = oldQuaternion;
  93243. });
  93244. impostor.physicsBody = this.world.add(bodyConfig);
  93245. // set the quaternion, ignoring the previously defined (euler) rotation
  93246. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  93247. // update with delta 0, so the body will reveive the new rotation.
  93248. impostor.physicsBody.updatePosition(0);
  93249. }
  93250. else {
  93251. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  93252. }
  93253. impostor.setDeltaPosition(this._tmpPositionVector);
  93254. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  93255. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  93256. };
  93257. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93258. //impostor.physicsBody.dispose();
  93259. //Same as : (older oimo versions)
  93260. this.world.removeRigidBody(impostor.physicsBody);
  93261. };
  93262. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93263. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93264. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93265. if (!mainBody || !connectedBody) {
  93266. return;
  93267. }
  93268. var jointData = impostorJoint.joint.jointData;
  93269. var options = jointData.nativeParams || {};
  93270. var type;
  93271. var nativeJointData = {
  93272. body1: mainBody,
  93273. body2: connectedBody,
  93274. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  93275. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  93276. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  93277. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  93278. min: options.min,
  93279. max: options.max,
  93280. collision: options.collision || jointData.collision,
  93281. spring: options.spring,
  93282. //supporting older version of Oimo
  93283. world: this.world
  93284. };
  93285. switch (impostorJoint.joint.type) {
  93286. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93287. type = "jointBall";
  93288. break;
  93289. case BABYLON.PhysicsJoint.SpringJoint:
  93290. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  93291. var springData = jointData;
  93292. nativeJointData.min = springData.length || nativeJointData.min;
  93293. //Max should also be set, just make sure it is at least min
  93294. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  93295. case BABYLON.PhysicsJoint.DistanceJoint:
  93296. type = "jointDistance";
  93297. nativeJointData.max = jointData.maxDistance;
  93298. break;
  93299. case BABYLON.PhysicsJoint.PrismaticJoint:
  93300. type = "jointPrisme";
  93301. break;
  93302. case BABYLON.PhysicsJoint.SliderJoint:
  93303. type = "jointSlide";
  93304. break;
  93305. case BABYLON.PhysicsJoint.WheelJoint:
  93306. type = "jointWheel";
  93307. break;
  93308. case BABYLON.PhysicsJoint.HingeJoint:
  93309. default:
  93310. type = "jointHinge";
  93311. break;
  93312. }
  93313. nativeJointData.type = type;
  93314. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  93315. };
  93316. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93317. //Bug in Oimo prevents us from disposing a joint in the playground
  93318. //joint.joint.physicsJoint.dispose();
  93319. //So we will bruteforce it!
  93320. try {
  93321. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  93322. }
  93323. catch (e) {
  93324. BABYLON.Tools.Warn(e);
  93325. }
  93326. };
  93327. OimoJSPlugin.prototype.isSupported = function () {
  93328. return this.BJSOIMO !== undefined;
  93329. };
  93330. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93331. if (!impostor.physicsBody.sleeping) {
  93332. //TODO check that
  93333. /*if (impostor.physicsBody.shapes.next) {
  93334. var parentShape = this._getLastShape(impostor.physicsBody);
  93335. impostor.object.position.copyFrom(parentShape.position);
  93336. console.log(parentShape.position);
  93337. } else {*/
  93338. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  93339. //}
  93340. if (impostor.object.rotationQuaternion) {
  93341. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  93342. }
  93343. }
  93344. };
  93345. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93346. var body = impostor.physicsBody;
  93347. body.position.copy(newPosition);
  93348. body.orientation.copy(newRotation);
  93349. body.syncShapes();
  93350. body.awake();
  93351. };
  93352. /*private _getLastShape(body: any): any {
  93353. var lastShape = body.shapes;
  93354. while (lastShape.next) {
  93355. lastShape = lastShape.next;
  93356. }
  93357. return lastShape;
  93358. }*/
  93359. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93360. impostor.physicsBody.linearVelocity.copy(velocity);
  93361. };
  93362. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93363. impostor.physicsBody.angularVelocity.copy(velocity);
  93364. };
  93365. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93366. var v = impostor.physicsBody.linearVelocity;
  93367. if (!v) {
  93368. return null;
  93369. }
  93370. return new BABYLON.Vector3(v.x, v.y, v.z);
  93371. };
  93372. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93373. var v = impostor.physicsBody.angularVelocity;
  93374. if (!v) {
  93375. return null;
  93376. }
  93377. return new BABYLON.Vector3(v.x, v.y, v.z);
  93378. };
  93379. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93380. var staticBody = mass === 0;
  93381. //this will actually set the body's density and not its mass.
  93382. //But this is how oimo treats the mass variable.
  93383. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  93384. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  93385. };
  93386. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  93387. return impostor.physicsBody.shapes.density;
  93388. };
  93389. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  93390. return impostor.physicsBody.shapes.friction;
  93391. };
  93392. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93393. impostor.physicsBody.shapes.friction = friction;
  93394. };
  93395. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93396. return impostor.physicsBody.shapes.restitution;
  93397. };
  93398. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93399. impostor.physicsBody.shapes.restitution = restitution;
  93400. };
  93401. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  93402. impostor.physicsBody.sleep();
  93403. };
  93404. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  93405. impostor.physicsBody.awake();
  93406. };
  93407. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93408. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  93409. if (minDistance !== void 0) {
  93410. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  93411. }
  93412. };
  93413. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93414. //TODO separate rotational and transational motors.
  93415. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93416. if (motor) {
  93417. motor.setMotor(speed, maxForce);
  93418. }
  93419. };
  93420. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  93421. //TODO separate rotational and transational motors.
  93422. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93423. if (motor) {
  93424. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  93425. }
  93426. };
  93427. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93428. var body = impostor.physicsBody;
  93429. mesh.position.x = body.position.x;
  93430. mesh.position.y = body.position.y;
  93431. mesh.position.z = body.position.z;
  93432. if (mesh.rotationQuaternion) {
  93433. mesh.rotationQuaternion.x = body.orientation.x;
  93434. mesh.rotationQuaternion.y = body.orientation.y;
  93435. mesh.rotationQuaternion.z = body.orientation.z;
  93436. mesh.rotationQuaternion.w = body.orientation.s;
  93437. }
  93438. };
  93439. OimoJSPlugin.prototype.getRadius = function (impostor) {
  93440. return impostor.physicsBody.shapes.radius;
  93441. };
  93442. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93443. var shape = impostor.physicsBody.shapes;
  93444. result.x = shape.halfWidth * 2;
  93445. result.y = shape.halfHeight * 2;
  93446. result.z = shape.halfDepth * 2;
  93447. };
  93448. OimoJSPlugin.prototype.dispose = function () {
  93449. this.world.clear();
  93450. };
  93451. return OimoJSPlugin;
  93452. }());
  93453. BABYLON.OimoJSPlugin = OimoJSPlugin;
  93454. })(BABYLON || (BABYLON = {}));
  93455. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  93456. var BABYLON;
  93457. (function (BABYLON) {
  93458. /**
  93459. * Gets the current physics engine
  93460. * @returns a IPhysicsEngine or null if none attached
  93461. */
  93462. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  93463. return this._physicsEngine;
  93464. };
  93465. /**
  93466. * Enables physics to the current scene
  93467. * @param gravity defines the scene's gravity for the physics engine
  93468. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  93469. * @return a boolean indicating if the physics engine was initialized
  93470. */
  93471. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  93472. if (gravity === void 0) { gravity = null; }
  93473. if (this._physicsEngine) {
  93474. return true;
  93475. }
  93476. // Register the component to the scene
  93477. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  93478. if (!component) {
  93479. component = new PhysicsEngineSceneComponent(this);
  93480. this._addComponent(component);
  93481. }
  93482. try {
  93483. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  93484. return true;
  93485. }
  93486. catch (e) {
  93487. BABYLON.Tools.Error(e.message);
  93488. return false;
  93489. }
  93490. };
  93491. /**
  93492. * Disables and disposes the physics engine associated with the scene
  93493. */
  93494. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  93495. if (!this._physicsEngine) {
  93496. return;
  93497. }
  93498. this._physicsEngine.dispose();
  93499. this._physicsEngine = null;
  93500. };
  93501. /**
  93502. * Gets a boolean indicating if there is an active physics engine
  93503. * @returns a boolean indicating if there is an active physics engine
  93504. */
  93505. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  93506. return this._physicsEngine !== undefined;
  93507. };
  93508. /**
  93509. * Deletes a physics compound impostor
  93510. * @param compound defines the compound to delete
  93511. */
  93512. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  93513. var mesh = compound.parts[0].mesh;
  93514. if (mesh.physicsImpostor) {
  93515. mesh.physicsImpostor.dispose( /*true*/);
  93516. mesh.physicsImpostor = null;
  93517. }
  93518. };
  93519. /** @hidden */
  93520. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  93521. if (this._physicsEngine) {
  93522. this.onBeforePhysicsObservable.notifyObservers(this);
  93523. this._physicsEngine._step(step / 1000);
  93524. this.onAfterPhysicsObservable.notifyObservers(this);
  93525. }
  93526. };
  93527. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  93528. get: function () {
  93529. return this._physicsImpostor;
  93530. },
  93531. set: function (value) {
  93532. var _this = this;
  93533. if (this._physicsImpostor === value) {
  93534. return;
  93535. }
  93536. if (this._disposePhysicsObserver) {
  93537. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  93538. }
  93539. this._physicsImpostor = value;
  93540. if (value) {
  93541. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  93542. // Physics
  93543. if (_this.physicsImpostor) {
  93544. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  93545. _this.physicsImpostor = null;
  93546. }
  93547. });
  93548. }
  93549. },
  93550. enumerable: true,
  93551. configurable: true
  93552. });
  93553. /**
  93554. * Gets the current physics impostor
  93555. * @see http://doc.babylonjs.com/features/physics_engine
  93556. * @returns a physics impostor or null
  93557. */
  93558. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  93559. return this.physicsImpostor;
  93560. };
  93561. /**
  93562. * Apply a physic impulse to the mesh
  93563. * @param force defines the force to apply
  93564. * @param contactPoint defines where to apply the force
  93565. * @returns the current mesh
  93566. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93567. */
  93568. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  93569. if (!this.physicsImpostor) {
  93570. return this;
  93571. }
  93572. this.physicsImpostor.applyImpulse(force, contactPoint);
  93573. return this;
  93574. };
  93575. /**
  93576. * Creates a physic joint between two meshes
  93577. * @param otherMesh defines the other mesh to use
  93578. * @param pivot1 defines the pivot to use on this mesh
  93579. * @param pivot2 defines the pivot to use on the other mesh
  93580. * @param options defines additional options (can be plugin dependent)
  93581. * @returns the current mesh
  93582. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  93583. */
  93584. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  93585. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  93586. return this;
  93587. }
  93588. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  93589. mainPivot: pivot1,
  93590. connectedPivot: pivot2,
  93591. nativeParams: options
  93592. });
  93593. return this;
  93594. };
  93595. /**
  93596. * Defines the physics engine scene component responsible to manage a physics engine
  93597. */
  93598. var PhysicsEngineSceneComponent = /** @class */ (function () {
  93599. /**
  93600. * Creates a new instance of the component for the given scene
  93601. * @param scene Defines the scene to register the component in
  93602. */
  93603. function PhysicsEngineSceneComponent(scene) {
  93604. var _this = this;
  93605. /**
  93606. * The component name helpful to identify the component in the list of scene components.
  93607. */
  93608. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  93609. this.scene = scene;
  93610. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  93611. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  93612. // Replace the function used to get the deterministic frame time
  93613. this.scene.getDeterministicFrameTime = function () {
  93614. if (_this.scene._physicsEngine) {
  93615. return _this.scene._physicsEngine.getTimeStep() * 1000;
  93616. }
  93617. return 1000.0 / 60.0;
  93618. };
  93619. }
  93620. /**
  93621. * Registers the component in a given scene
  93622. */
  93623. PhysicsEngineSceneComponent.prototype.register = function () {
  93624. };
  93625. /**
  93626. * Rebuilds the elements related to this component in case of
  93627. * context lost for instance.
  93628. */
  93629. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  93630. // Nothing to do for this component
  93631. };
  93632. /**
  93633. * Disposes the component and the associated ressources
  93634. */
  93635. PhysicsEngineSceneComponent.prototype.dispose = function () {
  93636. this.scene.onBeforePhysicsObservable.clear();
  93637. this.scene.onAfterPhysicsObservable.clear();
  93638. if (this.scene._physicsEngine) {
  93639. this.scene.disablePhysicsEngine();
  93640. }
  93641. };
  93642. return PhysicsEngineSceneComponent;
  93643. }());
  93644. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  93645. })(BABYLON || (BABYLON = {}));
  93646. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  93647. var BABYLON;
  93648. (function (BABYLON) {
  93649. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  93650. // All values and structures referenced from:
  93651. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  93652. var DDS_MAGIC = 0x20534444;
  93653. var
  93654. //DDSD_CAPS = 0x1,
  93655. //DDSD_HEIGHT = 0x2,
  93656. //DDSD_WIDTH = 0x4,
  93657. //DDSD_PITCH = 0x8,
  93658. //DDSD_PIXELFORMAT = 0x1000,
  93659. DDSD_MIPMAPCOUNT = 0x20000;
  93660. //DDSD_LINEARSIZE = 0x80000,
  93661. //DDSD_DEPTH = 0x800000;
  93662. // var DDSCAPS_COMPLEX = 0x8,
  93663. // DDSCAPS_MIPMAP = 0x400000,
  93664. // DDSCAPS_TEXTURE = 0x1000;
  93665. var DDSCAPS2_CUBEMAP = 0x200;
  93666. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  93667. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  93668. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  93669. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  93670. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  93671. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  93672. // DDSCAPS2_VOLUME = 0x200000;
  93673. var
  93674. //DDPF_ALPHAPIXELS = 0x1,
  93675. //DDPF_ALPHA = 0x2,
  93676. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  93677. //DDPF_YUV = 0x200,
  93678. DDPF_LUMINANCE = 0x20000;
  93679. function FourCCToInt32(value) {
  93680. return value.charCodeAt(0) +
  93681. (value.charCodeAt(1) << 8) +
  93682. (value.charCodeAt(2) << 16) +
  93683. (value.charCodeAt(3) << 24);
  93684. }
  93685. function Int32ToFourCC(value) {
  93686. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  93687. }
  93688. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  93689. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  93690. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  93691. var FOURCC_DX10 = FourCCToInt32("DX10");
  93692. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  93693. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  93694. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  93695. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  93696. var headerLengthInt = 31; // The header length in 32 bit ints
  93697. // Offsets into the header array
  93698. var off_magic = 0;
  93699. var off_size = 1;
  93700. var off_flags = 2;
  93701. var off_height = 3;
  93702. var off_width = 4;
  93703. var off_mipmapCount = 7;
  93704. var off_pfFlags = 20;
  93705. var off_pfFourCC = 21;
  93706. var off_RGBbpp = 22;
  93707. var off_RMask = 23;
  93708. var off_GMask = 24;
  93709. var off_BMask = 25;
  93710. var off_AMask = 26;
  93711. // var off_caps1 = 27;
  93712. var off_caps2 = 28;
  93713. // var off_caps3 = 29;
  93714. // var off_caps4 = 30;
  93715. var off_dxgiFormat = 32;
  93716. ;
  93717. var DDSTools = /** @class */ (function () {
  93718. function DDSTools() {
  93719. }
  93720. DDSTools.GetDDSInfo = function (arrayBuffer) {
  93721. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93722. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  93723. var mipmapCount = 1;
  93724. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  93725. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93726. }
  93727. var fourCC = header[off_pfFourCC];
  93728. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  93729. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93730. switch (fourCC) {
  93731. case FOURCC_D3DFMT_R16G16B16A16F:
  93732. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93733. break;
  93734. case FOURCC_D3DFMT_R32G32B32A32F:
  93735. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93736. break;
  93737. case FOURCC_DX10:
  93738. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  93739. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93740. break;
  93741. }
  93742. }
  93743. return {
  93744. width: header[off_width],
  93745. height: header[off_height],
  93746. mipmapCount: mipmapCount,
  93747. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  93748. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  93749. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  93750. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  93751. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  93752. dxgiFormat: dxgiFormat,
  93753. textureType: textureType
  93754. };
  93755. };
  93756. DDSTools._ToHalfFloat = function (value) {
  93757. if (!DDSTools._FloatView) {
  93758. DDSTools._FloatView = new Float32Array(1);
  93759. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  93760. }
  93761. DDSTools._FloatView[0] = value;
  93762. var x = DDSTools._Int32View[0];
  93763. var bits = (x >> 16) & 0x8000; /* Get the sign */
  93764. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  93765. var e = (x >> 23) & 0xff; /* Using int is faster here */
  93766. /* If zero, or denormal, or exponent underflows too much for a denormal
  93767. * half, return signed zero. */
  93768. if (e < 103) {
  93769. return bits;
  93770. }
  93771. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  93772. if (e > 142) {
  93773. bits |= 0x7c00;
  93774. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  93775. * not Inf, so make sure we set one mantissa bit too. */
  93776. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  93777. return bits;
  93778. }
  93779. /* If exponent underflows but not too much, return a denormal */
  93780. if (e < 113) {
  93781. m |= 0x0800;
  93782. /* Extra rounding may overflow and set mantissa to 0 and exponent
  93783. * to 1, which is OK. */
  93784. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  93785. return bits;
  93786. }
  93787. bits |= ((e - 112) << 10) | (m >> 1);
  93788. bits += m & 1;
  93789. return bits;
  93790. };
  93791. DDSTools._FromHalfFloat = function (value) {
  93792. var s = (value & 0x8000) >> 15;
  93793. var e = (value & 0x7C00) >> 10;
  93794. var f = value & 0x03FF;
  93795. if (e === 0) {
  93796. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  93797. }
  93798. else if (e == 0x1F) {
  93799. return f ? NaN : ((s ? -1 : 1) * Infinity);
  93800. }
  93801. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  93802. };
  93803. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93804. var destArray = new Float32Array(dataLength);
  93805. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93806. var index = 0;
  93807. for (var y = 0; y < height; y++) {
  93808. for (var x = 0; x < width; x++) {
  93809. var srcPos = (x + y * width) * 4;
  93810. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  93811. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  93812. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  93813. if (DDSTools.StoreLODInAlphaChannel) {
  93814. destArray[index + 3] = lod;
  93815. }
  93816. else {
  93817. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  93818. }
  93819. index += 4;
  93820. }
  93821. }
  93822. return destArray;
  93823. };
  93824. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93825. if (DDSTools.StoreLODInAlphaChannel) {
  93826. var destArray = new Uint16Array(dataLength);
  93827. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93828. var index = 0;
  93829. for (var y = 0; y < height; y++) {
  93830. for (var x = 0; x < width; x++) {
  93831. var srcPos = (x + y * width) * 4;
  93832. destArray[index] = srcData[srcPos];
  93833. destArray[index + 1] = srcData[srcPos + 1];
  93834. destArray[index + 2] = srcData[srcPos + 2];
  93835. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  93836. index += 4;
  93837. }
  93838. }
  93839. return destArray;
  93840. }
  93841. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  93842. };
  93843. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93844. if (DDSTools.StoreLODInAlphaChannel) {
  93845. var destArray = new Float32Array(dataLength);
  93846. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93847. var index = 0;
  93848. for (var y = 0; y < height; y++) {
  93849. for (var x = 0; x < width; x++) {
  93850. var srcPos = (x + y * width) * 4;
  93851. destArray[index] = srcData[srcPos];
  93852. destArray[index + 1] = srcData[srcPos + 1];
  93853. destArray[index + 2] = srcData[srcPos + 2];
  93854. destArray[index + 3] = lod;
  93855. index += 4;
  93856. }
  93857. }
  93858. return destArray;
  93859. }
  93860. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  93861. };
  93862. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93863. var destArray = new Uint8Array(dataLength);
  93864. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93865. var index = 0;
  93866. for (var y = 0; y < height; y++) {
  93867. for (var x = 0; x < width; x++) {
  93868. var srcPos = (x + y * width) * 4;
  93869. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  93870. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  93871. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  93872. if (DDSTools.StoreLODInAlphaChannel) {
  93873. destArray[index + 3] = lod;
  93874. }
  93875. else {
  93876. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  93877. }
  93878. index += 4;
  93879. }
  93880. }
  93881. return destArray;
  93882. };
  93883. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93884. var destArray = new Uint8Array(dataLength);
  93885. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93886. var index = 0;
  93887. for (var y = 0; y < height; y++) {
  93888. for (var x = 0; x < width; x++) {
  93889. var srcPos = (x + y * width) * 4;
  93890. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  93891. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  93892. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  93893. if (DDSTools.StoreLODInAlphaChannel) {
  93894. destArray[index + 3] = lod;
  93895. }
  93896. else {
  93897. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  93898. }
  93899. index += 4;
  93900. }
  93901. }
  93902. return destArray;
  93903. };
  93904. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  93905. var byteArray = new Uint8Array(dataLength);
  93906. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93907. var index = 0;
  93908. for (var y = 0; y < height; y++) {
  93909. for (var x = 0; x < width; x++) {
  93910. var srcPos = (x + y * width) * 4;
  93911. byteArray[index] = srcData[srcPos + rOffset];
  93912. byteArray[index + 1] = srcData[srcPos + gOffset];
  93913. byteArray[index + 2] = srcData[srcPos + bOffset];
  93914. byteArray[index + 3] = srcData[srcPos + aOffset];
  93915. index += 4;
  93916. }
  93917. }
  93918. return byteArray;
  93919. };
  93920. DDSTools._ExtractLongWordOrder = function (value) {
  93921. if (value === 0 || value === 255 || value === -16777216) {
  93922. return 0;
  93923. }
  93924. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  93925. };
  93926. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  93927. var byteArray = new Uint8Array(dataLength);
  93928. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93929. var index = 0;
  93930. for (var y = 0; y < height; y++) {
  93931. for (var x = 0; x < width; x++) {
  93932. var srcPos = (x + y * width) * 3;
  93933. byteArray[index] = srcData[srcPos + rOffset];
  93934. byteArray[index + 1] = srcData[srcPos + gOffset];
  93935. byteArray[index + 2] = srcData[srcPos + bOffset];
  93936. index += 3;
  93937. }
  93938. }
  93939. return byteArray;
  93940. };
  93941. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  93942. var byteArray = new Uint8Array(dataLength);
  93943. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93944. var index = 0;
  93945. for (var y = 0; y < height; y++) {
  93946. for (var x = 0; x < width; x++) {
  93947. var srcPos = (x + y * width);
  93948. byteArray[index] = srcData[srcPos];
  93949. index++;
  93950. }
  93951. }
  93952. return byteArray;
  93953. };
  93954. /**
  93955. * Uploads DDS Levels to a Babylon Texture
  93956. * @hidden
  93957. */
  93958. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  93959. if (lodIndex === void 0) { lodIndex = -1; }
  93960. var sphericalPolynomialFaces = null;
  93961. if (info.sphericalPolynomial) {
  93962. sphericalPolynomialFaces = new Array();
  93963. }
  93964. var ext = engine.getCaps().s3tc;
  93965. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93966. var fourCC, width, height, dataLength = 0, dataOffset;
  93967. var byteArray, mipmapCount, mip;
  93968. var internalCompressedFormat = 0;
  93969. var blockBytes = 1;
  93970. if (header[off_magic] !== DDS_MAGIC) {
  93971. BABYLON.Tools.Error("Invalid magic number in DDS header");
  93972. return;
  93973. }
  93974. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  93975. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  93976. return;
  93977. }
  93978. if (info.isCompressed && !ext) {
  93979. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  93980. return;
  93981. }
  93982. var bpp = header[off_RGBbpp];
  93983. dataOffset = header[off_size] + 4;
  93984. var computeFormats = false;
  93985. if (info.isFourCC) {
  93986. fourCC = header[off_pfFourCC];
  93987. switch (fourCC) {
  93988. case FOURCC_DXT1:
  93989. blockBytes = 8;
  93990. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  93991. break;
  93992. case FOURCC_DXT3:
  93993. blockBytes = 16;
  93994. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  93995. break;
  93996. case FOURCC_DXT5:
  93997. blockBytes = 16;
  93998. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  93999. break;
  94000. case FOURCC_D3DFMT_R16G16B16A16F:
  94001. computeFormats = true;
  94002. break;
  94003. case FOURCC_D3DFMT_R32G32B32A32F:
  94004. computeFormats = true;
  94005. break;
  94006. case FOURCC_DX10:
  94007. // There is an additionnal header so dataOffset need to be changed
  94008. dataOffset += 5 * 4; // 5 uints
  94009. var supported = false;
  94010. switch (info.dxgiFormat) {
  94011. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  94012. computeFormats = true;
  94013. supported = true;
  94014. break;
  94015. case DXGI_FORMAT_B8G8R8X8_UNORM:
  94016. info.isRGB = true;
  94017. info.isFourCC = false;
  94018. bpp = 32;
  94019. supported = true;
  94020. break;
  94021. }
  94022. if (supported) {
  94023. break;
  94024. }
  94025. default:
  94026. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  94027. return;
  94028. }
  94029. }
  94030. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  94031. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  94032. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  94033. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  94034. if (computeFormats) {
  94035. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  94036. }
  94037. mipmapCount = 1;
  94038. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  94039. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94040. }
  94041. for (var face = 0; face < faces; face++) {
  94042. width = header[off_width];
  94043. height = header[off_height];
  94044. for (mip = 0; mip < mipmapCount; ++mip) {
  94045. if (lodIndex === -1 || lodIndex === mip) {
  94046. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  94047. var i = (lodIndex === -1) ? mip : 0;
  94048. if (!info.isCompressed && info.isFourCC) {
  94049. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94050. dataLength = width * height * 4;
  94051. var floatArray = null;
  94052. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  94053. if (bpp === 128) {
  94054. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94055. if (sphericalPolynomialFaces && i == 0) {
  94056. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94057. }
  94058. }
  94059. else if (bpp === 64) {
  94060. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94061. if (sphericalPolynomialFaces && i == 0) {
  94062. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94063. }
  94064. }
  94065. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94066. }
  94067. else {
  94068. if (bpp === 128) {
  94069. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94070. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94071. if (sphericalPolynomialFaces && i == 0) {
  94072. sphericalPolynomialFaces.push(floatArray);
  94073. }
  94074. }
  94075. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  94076. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94077. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94078. if (sphericalPolynomialFaces && i == 0) {
  94079. sphericalPolynomialFaces.push(floatArray);
  94080. }
  94081. }
  94082. else { // 64
  94083. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94084. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94085. if (sphericalPolynomialFaces && i == 0) {
  94086. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94087. }
  94088. }
  94089. }
  94090. if (floatArray) {
  94091. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  94092. }
  94093. }
  94094. else if (info.isRGB) {
  94095. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94096. if (bpp === 24) {
  94097. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  94098. dataLength = width * height * 3;
  94099. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  94100. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94101. }
  94102. else { // 32
  94103. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94104. dataLength = width * height * 4;
  94105. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  94106. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94107. }
  94108. }
  94109. else if (info.isLuminance) {
  94110. var unpackAlignment = engine._getUnpackAlignement();
  94111. var unpaddedRowSize = width;
  94112. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  94113. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  94114. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  94115. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  94116. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94117. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94118. }
  94119. else {
  94120. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  94121. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  94122. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94123. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  94124. }
  94125. }
  94126. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  94127. width *= 0.5;
  94128. height *= 0.5;
  94129. width = Math.max(1.0, width);
  94130. height = Math.max(1.0, height);
  94131. }
  94132. if (currentFace !== undefined) {
  94133. // Loading a single face
  94134. break;
  94135. }
  94136. }
  94137. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  94138. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  94139. size: header[off_width],
  94140. right: sphericalPolynomialFaces[0],
  94141. left: sphericalPolynomialFaces[1],
  94142. up: sphericalPolynomialFaces[2],
  94143. down: sphericalPolynomialFaces[3],
  94144. front: sphericalPolynomialFaces[4],
  94145. back: sphericalPolynomialFaces[5],
  94146. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  94147. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94148. gammaSpace: false,
  94149. });
  94150. }
  94151. else {
  94152. info.sphericalPolynomial = undefined;
  94153. }
  94154. };
  94155. DDSTools.StoreLODInAlphaChannel = false;
  94156. return DDSTools;
  94157. }());
  94158. BABYLON.DDSTools = DDSTools;
  94159. })(BABYLON || (BABYLON = {}));
  94160. //# sourceMappingURL=babylon.dds.js.map
  94161. var BABYLON;
  94162. (function (BABYLON) {
  94163. /**
  94164. * Implementation of the DDS Texture Loader.
  94165. */
  94166. var DDSTextureLoader = /** @class */ (function () {
  94167. function DDSTextureLoader() {
  94168. /**
  94169. * Defines wether the loader supports cascade loading the different faces.
  94170. */
  94171. this.supportCascades = true;
  94172. }
  94173. /**
  94174. * This returns if the loader support the current file information.
  94175. * @param extension defines the file extension of the file being loaded
  94176. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94177. * @param fallback defines the fallback internal texture if any
  94178. * @param isBase64 defines whether the texture is encoded as a base64
  94179. * @param isBuffer defines whether the texture data are stored as a buffer
  94180. * @returns true if the loader can load the specified file
  94181. */
  94182. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94183. return extension.indexOf(".dds") === 0;
  94184. };
  94185. /**
  94186. * Transform the url before loading if required.
  94187. * @param rootUrl the url of the texture
  94188. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94189. * @returns the transformed texture
  94190. */
  94191. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94192. return rootUrl;
  94193. };
  94194. /**
  94195. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94196. * @param rootUrl the url of the texture
  94197. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94198. * @returns the fallback texture
  94199. */
  94200. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94201. return null;
  94202. };
  94203. /**
  94204. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94205. * @param data contains the texture data
  94206. * @param texture defines the BabylonJS internal texture
  94207. * @param createPolynomials will be true if polynomials have been requested
  94208. * @param onLoad defines the callback to trigger once the texture is ready
  94209. * @param onError defines the callback to trigger in case of error
  94210. */
  94211. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  94212. var engine = texture.getEngine();
  94213. var info;
  94214. var loadMipmap = false;
  94215. if (Array.isArray(imgs)) {
  94216. for (var index = 0; index < imgs.length; index++) {
  94217. var data_1 = imgs[index];
  94218. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  94219. texture.width = info.width;
  94220. texture.height = info.height;
  94221. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94222. engine._unpackFlipY(info.isCompressed);
  94223. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  94224. if (!info.isFourCC && info.mipmapCount === 1) {
  94225. engine.generateMipMapsForCubemap(texture);
  94226. }
  94227. }
  94228. }
  94229. else {
  94230. var data = imgs;
  94231. info = BABYLON.DDSTools.GetDDSInfo(data);
  94232. texture.width = info.width;
  94233. texture.height = info.height;
  94234. if (createPolynomials) {
  94235. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  94236. }
  94237. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94238. engine._unpackFlipY(info.isCompressed);
  94239. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  94240. if (!info.isFourCC && info.mipmapCount === 1) {
  94241. engine.generateMipMapsForCubemap(texture);
  94242. }
  94243. }
  94244. engine._setCubeMapTextureParams(loadMipmap);
  94245. texture.isReady = true;
  94246. if (onLoad) {
  94247. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  94248. }
  94249. };
  94250. /**
  94251. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94252. * @param data contains the texture data
  94253. * @param texture defines the BabylonJS internal texture
  94254. * @param callback defines the method to call once ready to upload
  94255. */
  94256. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  94257. var info = BABYLON.DDSTools.GetDDSInfo(data);
  94258. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  94259. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  94260. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  94261. });
  94262. };
  94263. return DDSTextureLoader;
  94264. }());
  94265. // Register the loader.
  94266. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  94267. })(BABYLON || (BABYLON = {}));
  94268. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  94269. var BABYLON;
  94270. (function (BABYLON) {
  94271. /*
  94272. * Based on jsTGALoader - Javascript loader for TGA file
  94273. * By Vincent Thibault
  94274. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  94275. */
  94276. var TGATools = /** @class */ (function () {
  94277. function TGATools() {
  94278. }
  94279. TGATools.GetTGAHeader = function (data) {
  94280. var offset = 0;
  94281. var header = {
  94282. id_length: data[offset++],
  94283. colormap_type: data[offset++],
  94284. image_type: data[offset++],
  94285. colormap_index: data[offset++] | data[offset++] << 8,
  94286. colormap_length: data[offset++] | data[offset++] << 8,
  94287. colormap_size: data[offset++],
  94288. origin: [
  94289. data[offset++] | data[offset++] << 8,
  94290. data[offset++] | data[offset++] << 8
  94291. ],
  94292. width: data[offset++] | data[offset++] << 8,
  94293. height: data[offset++] | data[offset++] << 8,
  94294. pixel_size: data[offset++],
  94295. flags: data[offset++]
  94296. };
  94297. return header;
  94298. };
  94299. /**
  94300. * Uploads TGA content to a Babylon Texture
  94301. * @hidden
  94302. */
  94303. TGATools.UploadContent = function (texture, data) {
  94304. // Not enough data to contain header ?
  94305. if (data.length < 19) {
  94306. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  94307. return;
  94308. }
  94309. // Read Header
  94310. var offset = 18;
  94311. var header = TGATools.GetTGAHeader(data);
  94312. // Assume it's a valid Targa file.
  94313. if (header.id_length + offset > data.length) {
  94314. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  94315. return;
  94316. }
  94317. // Skip not needed data
  94318. offset += header.id_length;
  94319. var use_rle = false;
  94320. var use_pal = false;
  94321. var use_grey = false;
  94322. // Get some informations.
  94323. switch (header.image_type) {
  94324. case TGATools._TYPE_RLE_INDEXED:
  94325. use_rle = true;
  94326. case TGATools._TYPE_INDEXED:
  94327. use_pal = true;
  94328. break;
  94329. case TGATools._TYPE_RLE_RGB:
  94330. use_rle = true;
  94331. case TGATools._TYPE_RGB:
  94332. // use_rgb = true;
  94333. break;
  94334. case TGATools._TYPE_RLE_GREY:
  94335. use_rle = true;
  94336. case TGATools._TYPE_GREY:
  94337. use_grey = true;
  94338. break;
  94339. }
  94340. var pixel_data;
  94341. // var numAlphaBits = header.flags & 0xf;
  94342. var pixel_size = header.pixel_size >> 3;
  94343. var pixel_total = header.width * header.height * pixel_size;
  94344. // Read palettes
  94345. var palettes;
  94346. if (use_pal) {
  94347. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  94348. }
  94349. // Read LRE
  94350. if (use_rle) {
  94351. pixel_data = new Uint8Array(pixel_total);
  94352. var c, count, i;
  94353. var localOffset = 0;
  94354. var pixels = new Uint8Array(pixel_size);
  94355. while (offset < pixel_total && localOffset < pixel_total) {
  94356. c = data[offset++];
  94357. count = (c & 0x7f) + 1;
  94358. // RLE pixels
  94359. if (c & 0x80) {
  94360. // Bind pixel tmp array
  94361. for (i = 0; i < pixel_size; ++i) {
  94362. pixels[i] = data[offset++];
  94363. }
  94364. // Copy pixel array
  94365. for (i = 0; i < count; ++i) {
  94366. pixel_data.set(pixels, localOffset + i * pixel_size);
  94367. }
  94368. localOffset += pixel_size * count;
  94369. }
  94370. // Raw pixels
  94371. else {
  94372. count *= pixel_size;
  94373. for (i = 0; i < count; ++i) {
  94374. pixel_data[localOffset + i] = data[offset++];
  94375. }
  94376. localOffset += count;
  94377. }
  94378. }
  94379. }
  94380. // RAW Pixels
  94381. else {
  94382. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  94383. }
  94384. // Load to texture
  94385. var x_start, y_start, x_step, y_step, y_end, x_end;
  94386. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  94387. default:
  94388. case TGATools._ORIGIN_UL:
  94389. x_start = 0;
  94390. x_step = 1;
  94391. x_end = header.width;
  94392. y_start = 0;
  94393. y_step = 1;
  94394. y_end = header.height;
  94395. break;
  94396. case TGATools._ORIGIN_BL:
  94397. x_start = 0;
  94398. x_step = 1;
  94399. x_end = header.width;
  94400. y_start = header.height - 1;
  94401. y_step = -1;
  94402. y_end = -1;
  94403. break;
  94404. case TGATools._ORIGIN_UR:
  94405. x_start = header.width - 1;
  94406. x_step = -1;
  94407. x_end = -1;
  94408. y_start = 0;
  94409. y_step = 1;
  94410. y_end = header.height;
  94411. break;
  94412. case TGATools._ORIGIN_BR:
  94413. x_start = header.width - 1;
  94414. x_step = -1;
  94415. x_end = -1;
  94416. y_start = header.height - 1;
  94417. y_step = -1;
  94418. y_end = -1;
  94419. break;
  94420. }
  94421. // Load the specify method
  94422. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  94423. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  94424. var engine = texture.getEngine();
  94425. engine._uploadDataToTextureDirectly(texture, imageData);
  94426. };
  94427. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94428. var image = pixel_data, colormap = palettes;
  94429. var width = header.width, height = header.height;
  94430. var color, i = 0, x, y;
  94431. var imageData = new Uint8Array(width * height * 4);
  94432. for (y = y_start; y !== y_end; y += y_step) {
  94433. for (x = x_start; x !== x_end; x += x_step, i++) {
  94434. color = image[i];
  94435. imageData[(x + width * y) * 4 + 3] = 255;
  94436. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  94437. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  94438. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  94439. }
  94440. }
  94441. return imageData;
  94442. };
  94443. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94444. var image = pixel_data;
  94445. var width = header.width, height = header.height;
  94446. var color, i = 0, x, y;
  94447. var imageData = new Uint8Array(width * height * 4);
  94448. for (y = y_start; y !== y_end; y += y_step) {
  94449. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94450. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  94451. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  94452. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  94453. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  94454. imageData[(x + width * y) * 4 + 0] = r;
  94455. imageData[(x + width * y) * 4 + 1] = g;
  94456. imageData[(x + width * y) * 4 + 2] = b;
  94457. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  94458. }
  94459. }
  94460. return imageData;
  94461. };
  94462. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94463. var image = pixel_data;
  94464. var width = header.width, height = header.height;
  94465. var i = 0, x, y;
  94466. var imageData = new Uint8Array(width * height * 4);
  94467. for (y = y_start; y !== y_end; y += y_step) {
  94468. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  94469. imageData[(x + width * y) * 4 + 3] = 255;
  94470. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94471. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94472. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94473. }
  94474. }
  94475. return imageData;
  94476. };
  94477. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94478. var image = pixel_data;
  94479. var width = header.width, height = header.height;
  94480. var i = 0, x, y;
  94481. var imageData = new Uint8Array(width * height * 4);
  94482. for (y = y_start; y !== y_end; y += y_step) {
  94483. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  94484. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94485. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94486. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94487. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  94488. }
  94489. }
  94490. return imageData;
  94491. };
  94492. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94493. var image = pixel_data;
  94494. var width = header.width, height = header.height;
  94495. var color, i = 0, x, y;
  94496. var imageData = new Uint8Array(width * height * 4);
  94497. for (y = y_start; y !== y_end; y += y_step) {
  94498. for (x = x_start; x !== x_end; x += x_step, i++) {
  94499. color = image[i];
  94500. imageData[(x + width * y) * 4 + 0] = color;
  94501. imageData[(x + width * y) * 4 + 1] = color;
  94502. imageData[(x + width * y) * 4 + 2] = color;
  94503. imageData[(x + width * y) * 4 + 3] = 255;
  94504. }
  94505. }
  94506. return imageData;
  94507. };
  94508. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94509. var image = pixel_data;
  94510. var width = header.width, height = header.height;
  94511. var i = 0, x, y;
  94512. var imageData = new Uint8Array(width * height * 4);
  94513. for (y = y_start; y !== y_end; y += y_step) {
  94514. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94515. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  94516. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  94517. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94518. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  94519. }
  94520. }
  94521. return imageData;
  94522. };
  94523. //private static _TYPE_NO_DATA = 0;
  94524. TGATools._TYPE_INDEXED = 1;
  94525. TGATools._TYPE_RGB = 2;
  94526. TGATools._TYPE_GREY = 3;
  94527. TGATools._TYPE_RLE_INDEXED = 9;
  94528. TGATools._TYPE_RLE_RGB = 10;
  94529. TGATools._TYPE_RLE_GREY = 11;
  94530. TGATools._ORIGIN_MASK = 0x30;
  94531. TGATools._ORIGIN_SHIFT = 0x04;
  94532. TGATools._ORIGIN_BL = 0x00;
  94533. TGATools._ORIGIN_BR = 0x01;
  94534. TGATools._ORIGIN_UL = 0x02;
  94535. TGATools._ORIGIN_UR = 0x03;
  94536. return TGATools;
  94537. }());
  94538. BABYLON.TGATools = TGATools;
  94539. })(BABYLON || (BABYLON = {}));
  94540. //# sourceMappingURL=babylon.tga.js.map
  94541. var BABYLON;
  94542. (function (BABYLON) {
  94543. /**
  94544. * Implementation of the TGA Texture Loader.
  94545. */
  94546. var TGATextureLoader = /** @class */ (function () {
  94547. function TGATextureLoader() {
  94548. /**
  94549. * Defines wether the loader supports cascade loading the different faces.
  94550. */
  94551. this.supportCascades = false;
  94552. }
  94553. /**
  94554. * This returns if the loader support the current file information.
  94555. * @param extension defines the file extension of the file being loaded
  94556. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94557. * @param fallback defines the fallback internal texture if any
  94558. * @param isBase64 defines whether the texture is encoded as a base64
  94559. * @param isBuffer defines whether the texture data are stored as a buffer
  94560. * @returns true if the loader can load the specified file
  94561. */
  94562. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94563. return extension.indexOf(".tga") === 0;
  94564. };
  94565. /**
  94566. * Transform the url before loading if required.
  94567. * @param rootUrl the url of the texture
  94568. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94569. * @returns the transformed texture
  94570. */
  94571. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94572. return rootUrl;
  94573. };
  94574. /**
  94575. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94576. * @param rootUrl the url of the texture
  94577. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94578. * @returns the fallback texture
  94579. */
  94580. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94581. return null;
  94582. };
  94583. /**
  94584. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94585. * @param data contains the texture data
  94586. * @param texture defines the BabylonJS internal texture
  94587. * @param createPolynomials will be true if polynomials have been requested
  94588. * @param onLoad defines the callback to trigger once the texture is ready
  94589. * @param onError defines the callback to trigger in case of error
  94590. */
  94591. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94592. throw ".env not supported in Cube.";
  94593. };
  94594. /**
  94595. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94596. * @param data contains the texture data
  94597. * @param texture defines the BabylonJS internal texture
  94598. * @param callback defines the method to call once ready to upload
  94599. */
  94600. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  94601. var uintData = new Uint8Array(data);
  94602. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  94603. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  94604. BABYLON.TGATools.UploadContent(texture, uintData);
  94605. });
  94606. };
  94607. return TGATextureLoader;
  94608. }());
  94609. // Register the loader.
  94610. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  94611. })(BABYLON || (BABYLON = {}));
  94612. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  94613. var BABYLON;
  94614. (function (BABYLON) {
  94615. /**
  94616. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  94617. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  94618. */
  94619. var KhronosTextureContainer = /** @class */ (function () {
  94620. /**
  94621. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  94622. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  94623. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  94624. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  94625. */
  94626. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  94627. this.arrayBuffer = arrayBuffer;
  94628. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  94629. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  94630. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  94631. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  94632. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  94633. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  94634. BABYLON.Tools.Error("texture missing KTX identifier");
  94635. return;
  94636. }
  94637. // load the reset of the header in native 32 bit int
  94638. var header = new Int32Array(this.arrayBuffer, 12, 13);
  94639. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  94640. var oppositeEndianess = header[0] === 0x01020304;
  94641. // read all the header elements in order they exist in the file, without modification (sans endainness)
  94642. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  94643. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  94644. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  94645. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  94646. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  94647. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  94648. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  94649. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  94650. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  94651. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  94652. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  94653. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  94654. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  94655. if (this.glType !== 0) {
  94656. BABYLON.Tools.Error("only compressed formats currently supported");
  94657. return;
  94658. }
  94659. else {
  94660. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  94661. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  94662. }
  94663. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  94664. BABYLON.Tools.Error("only 2D textures currently supported");
  94665. return;
  94666. }
  94667. if (this.numberOfArrayElements !== 0) {
  94668. BABYLON.Tools.Error("texture arrays not currently supported");
  94669. return;
  94670. }
  94671. if (this.numberOfFaces !== facesExpected) {
  94672. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  94673. return;
  94674. }
  94675. // we now have a completely validated file, so could use existence of loadType as success
  94676. // would need to make this more elaborate & adjust checks above to support more than one load type
  94677. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  94678. }
  94679. // not as fast hardware based, but will probably never need to use
  94680. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  94681. return ((val & 0xFF) << 24)
  94682. | ((val & 0xFF00) << 8)
  94683. | ((val >> 8) & 0xFF00)
  94684. | ((val >> 24) & 0xFF);
  94685. };
  94686. /**
  94687. * Uploads KTX content to a Babylon Texture.
  94688. * It is assumed that the texture has already been created & is currently bound
  94689. * @hidden
  94690. */
  94691. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  94692. switch (this.loadType) {
  94693. case KhronosTextureContainer.COMPRESSED_2D:
  94694. this._upload2DCompressedLevels(texture, loadMipmaps);
  94695. break;
  94696. case KhronosTextureContainer.TEX_2D:
  94697. case KhronosTextureContainer.COMPRESSED_3D:
  94698. case KhronosTextureContainer.TEX_3D:
  94699. }
  94700. };
  94701. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  94702. // initialize width & height for level 1
  94703. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  94704. var width = this.pixelWidth;
  94705. var height = this.pixelHeight;
  94706. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  94707. for (var level = 0; level < mipmapCount; level++) {
  94708. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  94709. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  94710. for (var face = 0; face < this.numberOfFaces; face++) {
  94711. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  94712. var engine = texture.getEngine();
  94713. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  94714. dataOffset += imageSize; // add size of the image for the next face/mipmap
  94715. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  94716. }
  94717. width = Math.max(1.0, width * 0.5);
  94718. height = Math.max(1.0, height * 0.5);
  94719. }
  94720. };
  94721. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  94722. // load types
  94723. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  94724. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  94725. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  94726. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  94727. return KhronosTextureContainer;
  94728. }());
  94729. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  94730. })(BABYLON || (BABYLON = {}));
  94731. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  94732. var BABYLON;
  94733. (function (BABYLON) {
  94734. /**
  94735. * Implementation of the KTX Texture Loader.
  94736. */
  94737. var KTXTextureLoader = /** @class */ (function () {
  94738. function KTXTextureLoader() {
  94739. /**
  94740. * Defines wether the loader supports cascade loading the different faces.
  94741. */
  94742. this.supportCascades = false;
  94743. }
  94744. /**
  94745. * This returns if the loader support the current file information.
  94746. * @param extension defines the file extension of the file being loaded
  94747. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94748. * @param fallback defines the fallback internal texture if any
  94749. * @param isBase64 defines whether the texture is encoded as a base64
  94750. * @param isBuffer defines whether the texture data are stored as a buffer
  94751. * @returns true if the loader can load the specified file
  94752. */
  94753. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94754. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  94755. return true;
  94756. }
  94757. return false;
  94758. };
  94759. /**
  94760. * Transform the url before loading if required.
  94761. * @param rootUrl the url of the texture
  94762. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94763. * @returns the transformed texture
  94764. */
  94765. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94766. var lastDot = rootUrl.lastIndexOf('.');
  94767. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  94768. };
  94769. /**
  94770. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94771. * @param rootUrl the url of the texture
  94772. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94773. * @returns the fallback texture
  94774. */
  94775. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94776. // remove the format appended to the rootUrl in the original createCubeTexture call.
  94777. var exp = new RegExp("" + textureFormatInUse + "$");
  94778. return rootUrl.replace(exp, "");
  94779. };
  94780. /**
  94781. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94782. * @param data contains the texture data
  94783. * @param texture defines the BabylonJS internal texture
  94784. * @param createPolynomials will be true if polynomials have been requested
  94785. * @param onLoad defines the callback to trigger once the texture is ready
  94786. * @param onError defines the callback to trigger in case of error
  94787. */
  94788. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94789. if (Array.isArray(data)) {
  94790. return;
  94791. }
  94792. var engine = texture.getEngine();
  94793. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  94794. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  94795. engine._unpackFlipY(true);
  94796. ktx.uploadLevels(texture, texture.generateMipMaps);
  94797. texture.width = ktx.pixelWidth;
  94798. texture.height = ktx.pixelHeight;
  94799. engine._setCubeMapTextureParams(loadMipmap);
  94800. texture.isReady = true;
  94801. };
  94802. /**
  94803. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94804. * @param data contains the texture data
  94805. * @param texture defines the BabylonJS internal texture
  94806. * @param callback defines the method to call once ready to upload
  94807. */
  94808. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  94809. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  94810. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  94811. ktx.uploadLevels(texture, texture.generateMipMaps);
  94812. });
  94813. };
  94814. return KTXTextureLoader;
  94815. }());
  94816. // Register the loader.
  94817. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  94818. })(BABYLON || (BABYLON = {}));
  94819. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  94820. var BABYLON;
  94821. (function (BABYLON) {
  94822. /**
  94823. * Sets of helpers addressing the serialization and deserialization of environment texture
  94824. * stored in a BabylonJS env file.
  94825. * Those files are usually stored as .env files.
  94826. */
  94827. var EnvironmentTextureTools = /** @class */ (function () {
  94828. function EnvironmentTextureTools() {
  94829. }
  94830. /**
  94831. * Gets the environment info from an env file.
  94832. * @param data The array buffer containing the .env bytes.
  94833. * @returns the environment file info (the json header) if successfully parsed.
  94834. */
  94835. EnvironmentTextureTools.GetEnvInfo = function (data) {
  94836. var dataView = new DataView(data);
  94837. var pos = 0;
  94838. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94839. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  94840. BABYLON.Tools.Error('Not a babylon environment map');
  94841. return null;
  94842. }
  94843. }
  94844. // Read json manifest - collect characters up to null terminator
  94845. var manifestString = '';
  94846. var charCode = 0x00;
  94847. while ((charCode = dataView.getUint8(pos++))) {
  94848. manifestString += String.fromCharCode(charCode);
  94849. }
  94850. var manifest = JSON.parse(manifestString);
  94851. if (manifest.specular) {
  94852. // Extend the header with the position of the payload.
  94853. manifest.specular.specularDataPosition = pos;
  94854. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  94855. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  94856. }
  94857. return manifest;
  94858. };
  94859. /**
  94860. * Creates an environment texture from a loaded cube texture.
  94861. * @param texture defines the cube texture to convert in env file
  94862. * @return a promise containing the environment data if succesfull.
  94863. */
  94864. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  94865. var _this = this;
  94866. var internalTexture = texture.getInternalTexture();
  94867. if (!internalTexture) {
  94868. return Promise.reject("The cube texture is invalid.");
  94869. }
  94870. if (!texture._prefiltered) {
  94871. return Promise.reject("The cube texture is invalid (not prefiltered).");
  94872. }
  94873. var engine = internalTexture.getEngine();
  94874. if (engine && engine.premultipliedAlpha) {
  94875. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  94876. }
  94877. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  94878. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  94879. }
  94880. var canvas = engine.getRenderingCanvas();
  94881. if (!canvas) {
  94882. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  94883. }
  94884. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94885. if (!engine.getCaps().textureFloatRender) {
  94886. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94887. if (!engine.getCaps().textureHalfFloatRender) {
  94888. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  94889. }
  94890. }
  94891. var cubeWidth = internalTexture.width;
  94892. var hostingScene = new BABYLON.Scene(engine);
  94893. var specularTextures = {};
  94894. var promises = [];
  94895. // Read and collect all mipmaps data from the cube.
  94896. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  94897. mipmapsCount = Math.round(mipmapsCount);
  94898. var _loop_1 = function (i) {
  94899. var faceWidth = Math.pow(2, mipmapsCount - i);
  94900. var _loop_2 = function (face) {
  94901. var data = texture.readPixels(face, i);
  94902. // Creates a temp texture with the face data.
  94903. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  94904. // And rgbdEncode them.
  94905. var promise = new Promise(function (resolve, reject) {
  94906. 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);
  94907. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94908. rgbdPostProcess.onApply = function (effect) {
  94909. effect._bindTexture("textureSampler", tempTexture);
  94910. };
  94911. // As the process needs to happen on the main canvas, keep track of the current size
  94912. var currentW = engine.getRenderWidth();
  94913. var currentH = engine.getRenderHeight();
  94914. // Set the desired size for the texture
  94915. engine.setSize(faceWidth, faceWidth);
  94916. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  94917. // Reading datas from WebGL
  94918. BABYLON.Tools.ToBlob(canvas, function (blob) {
  94919. var fileReader = new FileReader();
  94920. fileReader.onload = function (event) {
  94921. var arrayBuffer = event.target.result;
  94922. specularTextures[i * 6 + face] = arrayBuffer;
  94923. resolve();
  94924. };
  94925. fileReader.readAsArrayBuffer(blob);
  94926. });
  94927. // Reapply the previous canvas size
  94928. engine.setSize(currentW, currentH);
  94929. });
  94930. });
  94931. promises.push(promise);
  94932. };
  94933. // All faces of the cube.
  94934. for (var face = 0; face < 6; face++) {
  94935. _loop_2(face);
  94936. }
  94937. };
  94938. for (var i = 0; i <= mipmapsCount; i++) {
  94939. _loop_1(i);
  94940. }
  94941. // Once all the textures haves been collected as RGBD stored in PNGs
  94942. return Promise.all(promises).then(function () {
  94943. // We can delete the hosting scene keeping track of all the creation objects
  94944. hostingScene.dispose();
  94945. // Creates the json header for the env texture
  94946. var info = {
  94947. version: 1,
  94948. width: cubeWidth,
  94949. irradiance: _this._CreateEnvTextureIrradiance(texture),
  94950. specular: {
  94951. mipmaps: [],
  94952. lodGenerationScale: texture.lodGenerationScale
  94953. }
  94954. };
  94955. // Sets the specular image data information
  94956. var position = 0;
  94957. for (var i = 0; i <= mipmapsCount; i++) {
  94958. for (var face = 0; face < 6; face++) {
  94959. var byteLength = specularTextures[i * 6 + face].byteLength;
  94960. info.specular.mipmaps.push({
  94961. length: byteLength,
  94962. position: position
  94963. });
  94964. position += byteLength;
  94965. }
  94966. }
  94967. // Encode the JSON as an array buffer
  94968. var infoString = JSON.stringify(info);
  94969. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  94970. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  94971. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  94972. infoView[i] = infoString.charCodeAt(i);
  94973. }
  94974. // Ends up with a null terminator for easier parsing
  94975. infoView[infoString.length] = 0x00;
  94976. // Computes the final required size and creates the storage
  94977. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  94978. var finalBuffer = new ArrayBuffer(totalSize);
  94979. var finalBufferView = new Uint8Array(finalBuffer);
  94980. var dataView = new DataView(finalBuffer);
  94981. // Copy the magic bytes identifying the file in
  94982. var pos = 0;
  94983. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94984. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  94985. }
  94986. // Add the json info
  94987. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  94988. pos += infoBuffer.byteLength;
  94989. // Finally inserts the texture data
  94990. for (var i = 0; i <= mipmapsCount; i++) {
  94991. for (var face = 0; face < 6; face++) {
  94992. var dataBuffer = specularTextures[i * 6 + face];
  94993. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  94994. pos += dataBuffer.byteLength;
  94995. }
  94996. }
  94997. // Voila
  94998. return finalBuffer;
  94999. });
  95000. };
  95001. /**
  95002. * Creates a JSON representation of the spherical data.
  95003. * @param texture defines the texture containing the polynomials
  95004. * @return the JSON representation of the spherical info
  95005. */
  95006. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  95007. var polynmials = texture.sphericalPolynomial;
  95008. if (polynmials == null) {
  95009. return null;
  95010. }
  95011. return {
  95012. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  95013. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  95014. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  95015. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  95016. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  95017. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  95018. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  95019. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  95020. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  95021. };
  95022. };
  95023. /**
  95024. * Uploads the texture info contained in the env file to the GPU.
  95025. * @param texture defines the internal texture to upload to
  95026. * @param arrayBuffer defines the buffer cotaining the data to load
  95027. * @param info defines the texture info retrieved through the GetEnvInfo method
  95028. * @returns a promise
  95029. */
  95030. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  95031. if (info.version !== 1) {
  95032. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  95033. }
  95034. var specularInfo = info.specular;
  95035. if (!specularInfo) {
  95036. // Nothing else parsed so far
  95037. return Promise.resolve();
  95038. }
  95039. // Double checks the enclosed info
  95040. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  95041. mipmapsCount = Math.round(mipmapsCount) + 1;
  95042. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  95043. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  95044. }
  95045. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  95046. var imageData = new Array(mipmapsCount);
  95047. for (var i = 0; i < mipmapsCount; i++) {
  95048. imageData[i] = new Array(6);
  95049. for (var face = 0; face < 6; face++) {
  95050. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  95051. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  95052. }
  95053. }
  95054. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  95055. };
  95056. /**
  95057. * Uploads the levels of image data to the GPU.
  95058. * @param texture defines the internal texture to upload to
  95059. * @param imageData defines the array buffer views of image data [mipmap][face]
  95060. * @returns a promise
  95061. */
  95062. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  95063. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  95064. throw new Error("Texture size must be a power of two");
  95065. }
  95066. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  95067. // Gets everything ready.
  95068. var engine = texture.getEngine();
  95069. var expandTexture = false;
  95070. var generateNonLODTextures = false;
  95071. var rgbdPostProcess = null;
  95072. var cubeRtt = null;
  95073. var lodTextures = null;
  95074. var caps = engine.getCaps();
  95075. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95076. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95077. texture.generateMipMaps = true;
  95078. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  95079. // Add extra process if texture lod is not supported
  95080. if (!caps.textureLOD) {
  95081. expandTexture = false;
  95082. generateNonLODTextures = true;
  95083. lodTextures = {};
  95084. }
  95085. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  95086. else if (engine.webGLVersion < 2) {
  95087. expandTexture = false;
  95088. }
  95089. // If half float available we can uncompress the texture
  95090. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  95091. expandTexture = true;
  95092. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95093. }
  95094. // If full float available we can uncompress the texture
  95095. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  95096. expandTexture = true;
  95097. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95098. }
  95099. // Expand the texture if possible
  95100. if (expandTexture) {
  95101. // Simply run through the decode PP
  95102. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  95103. texture._isRGBD = false;
  95104. texture.invertY = false;
  95105. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  95106. generateDepthBuffer: false,
  95107. generateMipMaps: true,
  95108. generateStencilBuffer: false,
  95109. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  95110. type: texture.type,
  95111. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  95112. });
  95113. }
  95114. else {
  95115. texture._isRGBD = true;
  95116. texture.invertY = true;
  95117. // In case of missing support, applies the same patch than DDS files.
  95118. if (generateNonLODTextures) {
  95119. var mipSlices = 3;
  95120. var scale = texture._lodGenerationScale;
  95121. var offset = texture._lodGenerationOffset;
  95122. for (var i = 0; i < mipSlices; i++) {
  95123. //compute LOD from even spacing in smoothness (matching shader calculation)
  95124. var smoothness = i / (mipSlices - 1);
  95125. var roughness = 1 - smoothness;
  95126. var minLODIndex = offset; // roughness = 0
  95127. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  95128. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  95129. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  95130. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  95131. glTextureFromLod.isCube = true;
  95132. glTextureFromLod.invertY = true;
  95133. glTextureFromLod.generateMipMaps = false;
  95134. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  95135. // Wrap in a base texture for easy binding.
  95136. var lodTexture = new BABYLON.BaseTexture(null);
  95137. lodTexture.isCube = true;
  95138. lodTexture._texture = glTextureFromLod;
  95139. lodTextures[mipmapIndex] = lodTexture;
  95140. switch (i) {
  95141. case 0:
  95142. texture._lodTextureLow = lodTexture;
  95143. break;
  95144. case 1:
  95145. texture._lodTextureMid = lodTexture;
  95146. break;
  95147. case 2:
  95148. texture._lodTextureHigh = lodTexture;
  95149. break;
  95150. }
  95151. }
  95152. }
  95153. }
  95154. var promises = [];
  95155. var _loop_3 = function (i) {
  95156. var _loop_4 = function (face) {
  95157. // Constructs an image element from image data
  95158. var bytes = imageData[i][face];
  95159. var blob = new Blob([bytes], { type: 'image/png' });
  95160. var url = URL.createObjectURL(blob);
  95161. var image = new Image();
  95162. image.src = url;
  95163. // Enqueue promise to upload to the texture.
  95164. var promise = new Promise(function (resolve, reject) {
  95165. image.onload = function () {
  95166. if (expandTexture) {
  95167. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  95168. reject(message);
  95169. }, image);
  95170. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95171. // Uncompress the data to a RTT
  95172. rgbdPostProcess.onApply = function (effect) {
  95173. effect._bindTexture("textureSampler", tempTexture_1);
  95174. effect.setFloat2("scale", 1, 1);
  95175. };
  95176. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  95177. // Cleanup
  95178. engine.restoreDefaultFramebuffer();
  95179. tempTexture_1.dispose();
  95180. window.URL.revokeObjectURL(url);
  95181. resolve();
  95182. });
  95183. }
  95184. else {
  95185. engine._uploadImageToTexture(texture, image, face, i);
  95186. // Upload the face to the non lod texture support
  95187. if (generateNonLODTextures) {
  95188. var lodTexture = lodTextures[i];
  95189. if (lodTexture) {
  95190. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  95191. }
  95192. }
  95193. resolve();
  95194. }
  95195. };
  95196. image.onerror = function (error) {
  95197. reject(error);
  95198. };
  95199. });
  95200. promises.push(promise);
  95201. };
  95202. // All faces
  95203. for (var face = 0; face < 6; face++) {
  95204. _loop_4(face);
  95205. }
  95206. };
  95207. // All mipmaps up to provided number of images
  95208. for (var i = 0; i < imageData.length; i++) {
  95209. _loop_3(i);
  95210. }
  95211. // Fill remaining mipmaps with black textures.
  95212. if (imageData.length < mipmapsCount) {
  95213. var data = void 0;
  95214. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  95215. var dataLength = size * size * 4;
  95216. switch (texture.type) {
  95217. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  95218. data = new Uint8Array(dataLength);
  95219. break;
  95220. }
  95221. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  95222. data = new Uint16Array(dataLength);
  95223. break;
  95224. }
  95225. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  95226. data = new Float32Array(dataLength);
  95227. break;
  95228. }
  95229. }
  95230. for (var i = imageData.length; i < mipmapsCount; i++) {
  95231. for (var face = 0; face < 6; face++) {
  95232. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  95233. }
  95234. }
  95235. }
  95236. // Once all done, finishes the cleanup and return
  95237. return Promise.all(promises).then(function () {
  95238. // Release temp RTT.
  95239. if (cubeRtt) {
  95240. engine._releaseFramebufferObjects(cubeRtt);
  95241. cubeRtt._swapAndDie(texture);
  95242. }
  95243. // Release temp Post Process.
  95244. if (rgbdPostProcess) {
  95245. rgbdPostProcess.dispose();
  95246. }
  95247. // Flag internal texture as ready in case they are in use.
  95248. if (generateNonLODTextures) {
  95249. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  95250. texture._lodTextureHigh._texture.isReady = true;
  95251. }
  95252. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  95253. texture._lodTextureMid._texture.isReady = true;
  95254. }
  95255. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  95256. texture._lodTextureLow._texture.isReady = true;
  95257. }
  95258. }
  95259. });
  95260. };
  95261. /**
  95262. * Uploads spherical polynomials information to the texture.
  95263. * @param texture defines the texture we are trying to upload the information to
  95264. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  95265. */
  95266. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  95267. if (info.version !== 1) {
  95268. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  95269. }
  95270. var irradianceInfo = info.irradiance;
  95271. if (!irradianceInfo) {
  95272. return;
  95273. }
  95274. var sp = new BABYLON.SphericalPolynomial();
  95275. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  95276. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  95277. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  95278. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  95279. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  95280. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  95281. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  95282. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  95283. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  95284. texture._sphericalPolynomial = sp;
  95285. };
  95286. /**
  95287. * Magic number identifying the env file.
  95288. */
  95289. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  95290. return EnvironmentTextureTools;
  95291. }());
  95292. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  95293. })(BABYLON || (BABYLON = {}));
  95294. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  95295. var BABYLON;
  95296. (function (BABYLON) {
  95297. /**
  95298. * Implementation of the ENV Texture Loader.
  95299. */
  95300. var ENVTextureLoader = /** @class */ (function () {
  95301. function ENVTextureLoader() {
  95302. /**
  95303. * Defines wether the loader supports cascade loading the different faces.
  95304. */
  95305. this.supportCascades = false;
  95306. }
  95307. /**
  95308. * This returns if the loader support the current file information.
  95309. * @param extension defines the file extension of the file being loaded
  95310. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95311. * @param fallback defines the fallback internal texture if any
  95312. * @param isBase64 defines whether the texture is encoded as a base64
  95313. * @param isBuffer defines whether the texture data are stored as a buffer
  95314. * @returns true if the loader can load the specified file
  95315. */
  95316. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95317. return extension.indexOf(".env") === 0;
  95318. };
  95319. /**
  95320. * Transform the url before loading if required.
  95321. * @param rootUrl the url of the texture
  95322. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95323. * @returns the transformed texture
  95324. */
  95325. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95326. return rootUrl;
  95327. };
  95328. /**
  95329. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95330. * @param rootUrl the url of the texture
  95331. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95332. * @returns the fallback texture
  95333. */
  95334. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95335. return null;
  95336. };
  95337. /**
  95338. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95339. * @param data contains the texture data
  95340. * @param texture defines the BabylonJS internal texture
  95341. * @param createPolynomials will be true if polynomials have been requested
  95342. * @param onLoad defines the callback to trigger once the texture is ready
  95343. * @param onError defines the callback to trigger in case of error
  95344. */
  95345. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95346. if (Array.isArray(data)) {
  95347. return;
  95348. }
  95349. data = data;
  95350. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  95351. if (info) {
  95352. texture.width = info.width;
  95353. texture.height = info.width;
  95354. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  95355. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  95356. texture.isReady = true;
  95357. if (onLoad) {
  95358. onLoad();
  95359. }
  95360. });
  95361. }
  95362. else if (onError) {
  95363. onError("Can not parse the environment file", null);
  95364. }
  95365. };
  95366. /**
  95367. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95368. * @param data contains the texture data
  95369. * @param texture defines the BabylonJS internal texture
  95370. * @param callback defines the method to call once ready to upload
  95371. */
  95372. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  95373. throw ".env not supported in 2d.";
  95374. };
  95375. return ENVTextureLoader;
  95376. }());
  95377. // Register the loader.
  95378. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  95379. })(BABYLON || (BABYLON = {}));
  95380. //# sourceMappingURL=babylon.envTextureLoader.js.map
  95381. var BABYLON;
  95382. (function (BABYLON) {
  95383. /**
  95384. * Renders a layer on top of an existing scene
  95385. */
  95386. var UtilityLayerRenderer = /** @class */ (function () {
  95387. /**
  95388. * Instantiates a UtilityLayerRenderer
  95389. * @param originalScene the original scene that will be rendered on top of
  95390. */
  95391. function UtilityLayerRenderer(
  95392. /** the original scene that will be rendered on top of */
  95393. originalScene) {
  95394. var _this = this;
  95395. this.originalScene = originalScene;
  95396. this._pointerCaptures = {};
  95397. this._lastPointerEvents = {};
  95398. /**
  95399. * If the utility layer should automatically be rendered on top of existing scene
  95400. */
  95401. this.shouldRender = true;
  95402. /**
  95403. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  95404. */
  95405. this.onlyCheckPointerDownEvents = true;
  95406. /**
  95407. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  95408. */
  95409. this.processAllEvents = false;
  95410. /**
  95411. * Observable raised when the pointer move from the utility layer scene to the main scene
  95412. */
  95413. this.onPointerOutObservable = new BABYLON.Observable();
  95414. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  95415. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  95416. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  95417. this.utilityLayerScene._allowPostProcessClearColor = false;
  95418. originalScene.getEngine().scenes.pop();
  95419. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  95420. this.utilityLayerScene.detachControl();
  95421. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  95422. if (!_this.processAllEvents) {
  95423. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  95424. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  95425. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  95426. return;
  95427. }
  95428. }
  95429. var pointerEvent = (prePointerInfo.event);
  95430. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  95431. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95432. return;
  95433. }
  95434. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  95435. if (!prePointerInfo.ray && utilityScenePick) {
  95436. prePointerInfo.ray = utilityScenePick.ray;
  95437. }
  95438. // always fire the prepointer oversvable
  95439. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  95440. // allow every non pointer down event to flow to the utility layer
  95441. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  95442. if (!prePointerInfo.skipOnPointerObservable) {
  95443. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95444. }
  95445. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  95446. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95447. }
  95448. return;
  95449. }
  95450. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  95451. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  95452. if (utilityScenePick && utilityScenePick.hit) {
  95453. if (!prePointerInfo.skipOnPointerObservable) {
  95454. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95455. }
  95456. prePointerInfo.skipOnPointerObservable = true;
  95457. }
  95458. }
  95459. else {
  95460. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  95461. var pointerEvent_1 = (prePointerInfo.event);
  95462. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  95463. if (originalScenePick && utilityScenePick) {
  95464. // No pick in utility scene
  95465. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  95466. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95467. // We touched an utility mesh present in the main scene
  95468. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95469. prePointerInfo.skipOnPointerObservable = true;
  95470. }
  95471. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95472. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  95473. }
  95474. }
  95475. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  95476. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  95477. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  95478. // If a previous utility layer set this, do not unset this
  95479. if (!prePointerInfo.skipOnPointerObservable) {
  95480. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  95481. }
  95482. }
  95483. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  95484. // We have a pick in both scenes but main is closer than utility
  95485. // We touched an utility mesh present in the main scene
  95486. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95487. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95488. prePointerInfo.skipOnPointerObservable = true;
  95489. }
  95490. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  95491. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  95492. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  95493. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  95494. }
  95495. }
  95496. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  95497. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  95498. }
  95499. }
  95500. }
  95501. });
  95502. // Render directly on top of existing scene without clearing
  95503. this.utilityLayerScene.autoClear = false;
  95504. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  95505. if (_this.shouldRender) {
  95506. _this.render();
  95507. }
  95508. });
  95509. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  95510. _this.dispose();
  95511. });
  95512. this._updateCamera();
  95513. }
  95514. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  95515. /**
  95516. * 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)
  95517. */
  95518. get: function () {
  95519. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  95520. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95521. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95522. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95523. });
  95524. }
  95525. return UtilityLayerRenderer._DefaultUtilityLayer;
  95526. },
  95527. enumerable: true,
  95528. configurable: true
  95529. });
  95530. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  95531. /**
  95532. * 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)
  95533. */
  95534. get: function () {
  95535. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  95536. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95537. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  95538. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95539. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95540. });
  95541. }
  95542. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  95543. },
  95544. enumerable: true,
  95545. configurable: true
  95546. });
  95547. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  95548. if (!prePointerInfo.skipOnPointerObservable) {
  95549. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  95550. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  95551. }
  95552. };
  95553. /**
  95554. * Renders the utility layers scene on top of the original scene
  95555. */
  95556. UtilityLayerRenderer.prototype.render = function () {
  95557. this._updateCamera();
  95558. if (this.utilityLayerScene.activeCamera) {
  95559. // Set the camera's scene to utility layers scene
  95560. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  95561. var camera = this.utilityLayerScene.activeCamera;
  95562. camera._scene = this.utilityLayerScene;
  95563. if (camera.leftCamera) {
  95564. camera.leftCamera._scene = this.utilityLayerScene;
  95565. }
  95566. if (camera.rightCamera) {
  95567. camera.rightCamera._scene = this.utilityLayerScene;
  95568. }
  95569. this.utilityLayerScene.render(false);
  95570. // Reset camera's scene back to original
  95571. camera._scene = oldScene;
  95572. if (camera.leftCamera) {
  95573. camera.leftCamera._scene = oldScene;
  95574. }
  95575. if (camera.rightCamera) {
  95576. camera.rightCamera._scene = oldScene;
  95577. }
  95578. }
  95579. };
  95580. /**
  95581. * Disposes of the renderer
  95582. */
  95583. UtilityLayerRenderer.prototype.dispose = function () {
  95584. this.onPointerOutObservable.clear();
  95585. if (this._afterRenderObserver) {
  95586. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  95587. }
  95588. if (this._sceneDisposeObserver) {
  95589. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95590. }
  95591. if (this._originalPointerObserver) {
  95592. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  95593. }
  95594. this.utilityLayerScene.dispose();
  95595. };
  95596. UtilityLayerRenderer.prototype._updateCamera = function () {
  95597. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  95598. };
  95599. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95600. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95601. return UtilityLayerRenderer;
  95602. }());
  95603. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  95604. })(BABYLON || (BABYLON = {}));
  95605. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  95606. //# sourceMappingURL=babylon.behavior.js.map
  95607. var BABYLON;
  95608. (function (BABYLON) {
  95609. /**
  95610. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95611. */
  95612. var PointerDragBehavior = /** @class */ (function () {
  95613. /**
  95614. * Creates a pointer drag behavior that can be attached to a mesh
  95615. * @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)
  95616. */
  95617. function PointerDragBehavior(options) {
  95618. /**
  95619. * 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)
  95620. */
  95621. this.maxDragAngle = 0;
  95622. /**
  95623. * @hidden
  95624. */
  95625. this._useAlternatePickedPointAboveMaxDragAngle = false;
  95626. /**
  95627. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95628. */
  95629. this.currentDraggingPointerID = -1;
  95630. /**
  95631. * If the behavior is currently in a dragging state
  95632. */
  95633. this.dragging = false;
  95634. /**
  95635. * 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)
  95636. */
  95637. this.dragDeltaRatio = 0.2;
  95638. /**
  95639. * If the drag plane orientation should be updated during the dragging (Default: true)
  95640. */
  95641. this.updateDragPlane = true;
  95642. // Debug mode will display drag planes to help visualize behavior
  95643. this._debugMode = false;
  95644. this._moving = false;
  95645. /**
  95646. * Fires each time the attached mesh is dragged with the pointer
  95647. * * delta between last drag position and current drag position in world space
  95648. * * dragDistance along the drag axis
  95649. * * dragPlaneNormal normal of the current drag plane used during the drag
  95650. * * dragPlanePoint in world space where the drag intersects the drag plane
  95651. */
  95652. this.onDragObservable = new BABYLON.Observable();
  95653. /**
  95654. * Fires each time a drag begins (eg. mouse down on mesh)
  95655. */
  95656. this.onDragStartObservable = new BABYLON.Observable();
  95657. /**
  95658. * Fires each time a drag ends (eg. mouse release after drag)
  95659. */
  95660. this.onDragEndObservable = new BABYLON.Observable();
  95661. /**
  95662. * If the attached mesh should be moved when dragged
  95663. */
  95664. this.moveAttached = true;
  95665. /**
  95666. * If the drag behavior will react to drag events (Default: true)
  95667. */
  95668. this.enabled = true;
  95669. /**
  95670. * If camera controls should be detached during the drag
  95671. */
  95672. this.detachCameraControls = true;
  95673. /**
  95674. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  95675. */
  95676. this.useObjectOrienationForDragging = true;
  95677. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95678. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  95679. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  95680. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95681. this._attachedElement = null;
  95682. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95683. this._lastPointerRay = {};
  95684. this._dragDelta = new BABYLON.Vector3();
  95685. // Variables to avoid instantiation in the below method
  95686. this._pointA = new BABYLON.Vector3(0, 0, 0);
  95687. this._pointB = new BABYLON.Vector3(0, 0, 0);
  95688. this._pointC = new BABYLON.Vector3(0, 0, 0);
  95689. this._lineA = new BABYLON.Vector3(0, 0, 0);
  95690. this._lineB = new BABYLON.Vector3(0, 0, 0);
  95691. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  95692. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  95693. this._options = options ? options : {};
  95694. var optionCount = 0;
  95695. if (this._options.dragAxis) {
  95696. optionCount++;
  95697. }
  95698. if (this._options.dragPlaneNormal) {
  95699. optionCount++;
  95700. }
  95701. if (optionCount > 1) {
  95702. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95703. }
  95704. }
  95705. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95706. /**
  95707. * The name of the behavior
  95708. */
  95709. get: function () {
  95710. return "PointerDrag";
  95711. },
  95712. enumerable: true,
  95713. configurable: true
  95714. });
  95715. /**
  95716. * Initializes the behavior
  95717. */
  95718. PointerDragBehavior.prototype.init = function () { };
  95719. /**
  95720. * Attaches the drag behavior the passed in mesh
  95721. * @param ownerNode The mesh that will be dragged around once attached
  95722. */
  95723. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95724. var _this = this;
  95725. this._scene = ownerNode.getScene();
  95726. this._attachedNode = ownerNode;
  95727. // Initialize drag plane to not interfere with existing scene
  95728. if (!PointerDragBehavior._planeScene) {
  95729. if (this._debugMode) {
  95730. PointerDragBehavior._planeScene = this._scene;
  95731. }
  95732. else {
  95733. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95734. PointerDragBehavior._planeScene.detachControl();
  95735. this._scene.getEngine().scenes.pop();
  95736. this._scene.onDisposeObservable.addOnce(function () {
  95737. PointerDragBehavior._planeScene.dispose();
  95738. PointerDragBehavior._planeScene = null;
  95739. });
  95740. }
  95741. }
  95742. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95743. // State of the drag
  95744. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  95745. var pickPredicate = function (m) {
  95746. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95747. };
  95748. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95749. if (!_this.enabled) {
  95750. return;
  95751. }
  95752. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95753. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95754. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  95755. }
  95756. }
  95757. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95758. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95759. _this.releaseDrag();
  95760. }
  95761. }
  95762. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95763. var pointerId = pointerInfo.event.pointerId;
  95764. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  95765. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  95766. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  95767. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  95768. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  95769. }
  95770. _this.currentDraggingPointerID = pointerId;
  95771. }
  95772. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  95773. if (!_this._lastPointerRay[pointerId]) {
  95774. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95775. }
  95776. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  95777. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  95778. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  95779. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  95780. _this._moveDrag(pointerInfo.pickInfo.ray);
  95781. }
  95782. }
  95783. }
  95784. });
  95785. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95786. if (_this._moving && _this.moveAttached) {
  95787. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  95788. // Slowly move mesh to avoid jitter
  95789. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  95790. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  95791. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  95792. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  95793. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  95794. }
  95795. });
  95796. };
  95797. /**
  95798. * Force relase the drag action by code.
  95799. */
  95800. PointerDragBehavior.prototype.releaseDrag = function () {
  95801. this.dragging = false;
  95802. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  95803. this.currentDraggingPointerID = -1;
  95804. this._moving = false;
  95805. // Reattach camera controls
  95806. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95807. this._scene.activeCamera.attachControl(this._attachedElement, true);
  95808. }
  95809. };
  95810. /**
  95811. * Simulates the start of a pointer drag event on the behavior
  95812. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  95813. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  95814. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  95815. */
  95816. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  95817. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  95818. this._startDrag(pointerId, fromRay, startPickedPoint);
  95819. var lastRay = this._lastPointerRay[pointerId];
  95820. if (pointerId === PointerDragBehavior._AnyMouseID) {
  95821. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  95822. }
  95823. if (lastRay) {
  95824. // if there was a last pointer ray drag the object there
  95825. this._moveDrag(lastRay);
  95826. }
  95827. };
  95828. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  95829. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  95830. return;
  95831. }
  95832. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  95833. // Create start ray from the camera to the object
  95834. if (fromRay) {
  95835. this._startDragRay.direction.copyFrom(fromRay.direction);
  95836. this._startDragRay.origin.copyFrom(fromRay.origin);
  95837. }
  95838. else {
  95839. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  95840. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  95841. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  95842. }
  95843. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  95844. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  95845. if (pickedPoint) {
  95846. this.dragging = true;
  95847. this.currentDraggingPointerID = pointerId;
  95848. this.lastDragPosition.copyFrom(pickedPoint);
  95849. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  95850. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  95851. // Detatch camera controls
  95852. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95853. if (this._scene.activeCamera.inputs.attachedElement) {
  95854. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  95855. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  95856. }
  95857. else {
  95858. this._attachedElement = null;
  95859. }
  95860. }
  95861. }
  95862. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  95863. };
  95864. PointerDragBehavior.prototype._moveDrag = function (ray) {
  95865. this._moving = true;
  95866. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  95867. if (pickedPoint) {
  95868. if (this.updateDragPlane) {
  95869. this._updateDragPlanePosition(ray, pickedPoint);
  95870. }
  95871. var dragLength = 0;
  95872. // depending on the drag mode option drag accordingly
  95873. if (this._options.dragAxis) {
  95874. // Convert local drag axis to world
  95875. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  95876. // Project delta drag from the drag plane onto the drag axis
  95877. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  95878. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  95879. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  95880. }
  95881. else {
  95882. dragLength = this._dragDelta.length();
  95883. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  95884. }
  95885. this._targetPosition.addInPlace(this._dragDelta);
  95886. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  95887. this.lastDragPosition.copyFrom(pickedPoint);
  95888. }
  95889. };
  95890. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95891. var _this = this;
  95892. if (!ray) {
  95893. return null;
  95894. }
  95895. // Calculate angle between plane normal and ray
  95896. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  95897. // Correct if ray is casted from oposite side
  95898. if (angle > Math.PI / 2) {
  95899. angle = Math.PI - angle;
  95900. }
  95901. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  95902. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  95903. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  95904. // Invert ray direction along the towards object axis
  95905. this._tmpVector.copyFrom(ray.direction);
  95906. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  95907. this._alternatePickedPoint.normalize();
  95908. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  95909. this._tmpVector.addInPlace(this._alternatePickedPoint);
  95910. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  95911. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  95912. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  95913. this._alternatePickedPoint.addInPlace(this._tmpVector);
  95914. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  95915. return this._alternatePickedPoint;
  95916. }
  95917. else {
  95918. return null;
  95919. }
  95920. }
  95921. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95922. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95923. return pickResult.pickedPoint;
  95924. }
  95925. else {
  95926. return null;
  95927. }
  95928. };
  95929. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95930. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  95931. this._pointA.copyFrom(dragPlanePosition);
  95932. if (this._options.dragAxis) {
  95933. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  95934. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95935. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  95936. ray.origin.subtractToRef(this._pointA, this._pointC);
  95937. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  95938. // Get perpendicular line from direction to camera and drag axis
  95939. this._pointB.subtractToRef(this._pointA, this._lineA);
  95940. this._pointC.subtractToRef(this._pointA, this._lineB);
  95941. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  95942. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95943. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  95944. this._lookAt.normalize();
  95945. this._dragPlane.position.copyFrom(this._pointA);
  95946. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  95947. this._dragPlane.lookAt(this._lookAt);
  95948. }
  95949. else if (this._options.dragPlaneNormal) {
  95950. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  95951. this._dragPlane.position.copyFrom(this._pointA);
  95952. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  95953. this._dragPlane.lookAt(this._lookAt);
  95954. }
  95955. else {
  95956. this._dragPlane.position.copyFrom(this._pointA);
  95957. this._dragPlane.lookAt(ray.origin);
  95958. }
  95959. this._dragPlane.computeWorldMatrix(true);
  95960. };
  95961. /**
  95962. * Detaches the behavior from the mesh
  95963. */
  95964. PointerDragBehavior.prototype.detach = function () {
  95965. if (this._pointerObserver) {
  95966. this._scene.onPointerObservable.remove(this._pointerObserver);
  95967. }
  95968. if (this._beforeRenderObserver) {
  95969. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95970. }
  95971. };
  95972. PointerDragBehavior._AnyMouseID = -2;
  95973. return PointerDragBehavior;
  95974. }());
  95975. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95976. })(BABYLON || (BABYLON = {}));
  95977. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95978. var BABYLON;
  95979. (function (BABYLON) {
  95980. /**
  95981. * A behavior that when attached to a mesh will allow the mesh to be scaled
  95982. */
  95983. var MultiPointerScaleBehavior = /** @class */ (function () {
  95984. /**
  95985. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  95986. */
  95987. function MultiPointerScaleBehavior() {
  95988. this._startDistance = 0;
  95989. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  95990. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  95991. this._sceneRenderObserver = null;
  95992. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  95993. this._dragBehaviorA.moveAttached = false;
  95994. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  95995. this._dragBehaviorB.moveAttached = false;
  95996. }
  95997. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  95998. /**
  95999. * The name of the behavior
  96000. */
  96001. get: function () {
  96002. return "MultiPointerScale";
  96003. },
  96004. enumerable: true,
  96005. configurable: true
  96006. });
  96007. /**
  96008. * Initializes the behavior
  96009. */
  96010. MultiPointerScaleBehavior.prototype.init = function () { };
  96011. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  96012. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  96013. };
  96014. /**
  96015. * Attaches the scale behavior the passed in mesh
  96016. * @param ownerNode The mesh that will be scaled around once attached
  96017. */
  96018. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  96019. var _this = this;
  96020. this._ownerNode = ownerNode;
  96021. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  96022. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  96023. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96024. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96025. _this._dragBehaviorA.releaseDrag();
  96026. }
  96027. else {
  96028. _this._initialScale.copyFrom(ownerNode.scaling);
  96029. _this._startDistance = _this._getCurrentDistance();
  96030. }
  96031. }
  96032. });
  96033. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  96034. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96035. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96036. _this._dragBehaviorB.releaseDrag();
  96037. }
  96038. else {
  96039. _this._initialScale.copyFrom(ownerNode.scaling);
  96040. _this._startDistance = _this._getCurrentDistance();
  96041. }
  96042. }
  96043. });
  96044. // Once both drag behaviors are active scale based on the distance between the two pointers
  96045. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96046. behavior.onDragObservable.add(function () {
  96047. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96048. var ratio = _this._getCurrentDistance() / _this._startDistance;
  96049. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  96050. }
  96051. });
  96052. });
  96053. ownerNode.addBehavior(this._dragBehaviorA);
  96054. ownerNode.addBehavior(this._dragBehaviorB);
  96055. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96056. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96057. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96058. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  96059. if (change.length() > 0.01) {
  96060. ownerNode.scaling.addInPlace(change);
  96061. }
  96062. }
  96063. });
  96064. };
  96065. /**
  96066. * Detaches the behavior from the mesh
  96067. */
  96068. MultiPointerScaleBehavior.prototype.detach = function () {
  96069. var _this = this;
  96070. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96071. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96072. behavior.onDragStartObservable.clear();
  96073. behavior.onDragObservable.clear();
  96074. _this._ownerNode.removeBehavior(behavior);
  96075. });
  96076. };
  96077. return MultiPointerScaleBehavior;
  96078. }());
  96079. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  96080. })(BABYLON || (BABYLON = {}));
  96081. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  96082. var BABYLON;
  96083. (function (BABYLON) {
  96084. /**
  96085. * 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
  96086. */
  96087. var SixDofDragBehavior = /** @class */ (function () {
  96088. /**
  96089. * 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
  96090. */
  96091. function SixDofDragBehavior() {
  96092. this._sceneRenderObserver = null;
  96093. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96094. this._moving = false;
  96095. this._startingOrientation = new BABYLON.Quaternion();
  96096. /**
  96097. * 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)
  96098. */
  96099. this.zDragFactor = 3;
  96100. /**
  96101. * If the behavior is currently in a dragging state
  96102. */
  96103. this.dragging = false;
  96104. /**
  96105. * 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)
  96106. */
  96107. this.dragDeltaRatio = 0.2;
  96108. /**
  96109. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96110. */
  96111. this.currentDraggingPointerID = -1;
  96112. /**
  96113. * If camera controls should be detached during the drag
  96114. */
  96115. this.detachCameraControls = true;
  96116. /**
  96117. * Fires each time a drag starts
  96118. */
  96119. this.onDragStartObservable = new BABYLON.Observable();
  96120. /**
  96121. * Fires each time a drag ends (eg. mouse release after drag)
  96122. */
  96123. this.onDragEndObservable = new BABYLON.Observable();
  96124. }
  96125. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  96126. /**
  96127. * The name of the behavior
  96128. */
  96129. get: function () {
  96130. return "SixDofDrag";
  96131. },
  96132. enumerable: true,
  96133. configurable: true
  96134. });
  96135. /**
  96136. * Initializes the behavior
  96137. */
  96138. SixDofDragBehavior.prototype.init = function () { };
  96139. /**
  96140. * Attaches the scale behavior the passed in mesh
  96141. * @param ownerNode The mesh that will be scaled around once attached
  96142. */
  96143. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  96144. var _this = this;
  96145. this._ownerNode = ownerNode;
  96146. this._scene = this._ownerNode.getScene();
  96147. if (!SixDofDragBehavior._virtualScene) {
  96148. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  96149. this._scene.getEngine().scenes.pop();
  96150. }
  96151. var pickedMesh = null;
  96152. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  96153. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  96154. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96155. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  96156. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96157. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  96158. var pickPredicate = function (m) {
  96159. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  96160. };
  96161. var attachedElement = null;
  96162. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96163. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96164. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96165. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96166. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96167. }
  96168. pickedMesh = _this._ownerNode;
  96169. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96170. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96171. // Set position and orientation of the controller
  96172. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96173. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96174. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  96175. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96176. pickedMesh.computeWorldMatrix();
  96177. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  96178. if (!pickedMesh.rotationQuaternion) {
  96179. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  96180. }
  96181. var oldParent = pickedMesh.parent;
  96182. pickedMesh.setParent(null);
  96183. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  96184. pickedMesh.setParent(oldParent);
  96185. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96186. // Update state
  96187. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96188. _this.dragging = true;
  96189. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  96190. // Detatch camera controls
  96191. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96192. if (_this._scene.activeCamera.inputs.attachedElement) {
  96193. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  96194. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  96195. }
  96196. else {
  96197. attachedElement = null;
  96198. }
  96199. }
  96200. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96201. _this.onDragStartObservable.notifyObservers({});
  96202. }
  96203. }
  96204. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96205. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96206. _this.dragging = false;
  96207. _this._moving = false;
  96208. _this.currentDraggingPointerID = -1;
  96209. pickedMesh = null;
  96210. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96211. // Reattach camera controls
  96212. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96213. _this._scene.activeCamera.attachControl(attachedElement, true);
  96214. }
  96215. _this.onDragEndObservable.notifyObservers({});
  96216. }
  96217. }
  96218. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96219. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  96220. var zDragFactor = _this.zDragFactor;
  96221. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96222. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96223. zDragFactor = 0;
  96224. }
  96225. // Calculate controller drag distance in controller space
  96226. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  96227. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96228. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  96229. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96230. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  96231. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  96232. if (_this._virtualDragMesh.position.z < 0) {
  96233. _this._virtualDragMesh.position.z = 0;
  96234. }
  96235. // Update the controller position
  96236. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96237. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96238. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96239. // Move the virtualObjectsPosition into the picked mesh's space if needed
  96240. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96241. if (pickedMesh.parent) {
  96242. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  96243. }
  96244. if (!_this._moving) {
  96245. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  96246. }
  96247. _this._moving = true;
  96248. }
  96249. }
  96250. });
  96251. var tmpQuaternion = new BABYLON.Quaternion();
  96252. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96253. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96254. if (_this.dragging && _this._moving && pickedMesh) {
  96255. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96256. // Slowly move mesh to avoid jitter
  96257. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  96258. // Get change in rotation
  96259. tmpQuaternion.copyFrom(_this._startingOrientation);
  96260. tmpQuaternion.x = -tmpQuaternion.x;
  96261. tmpQuaternion.y = -tmpQuaternion.y;
  96262. tmpQuaternion.z = -tmpQuaternion.z;
  96263. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  96264. // Convert change in rotation to only y axis rotation
  96265. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  96266. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  96267. // Slowly move mesh to avoid jitter
  96268. var oldParent = pickedMesh.parent;
  96269. pickedMesh.setParent(null);
  96270. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  96271. pickedMesh.setParent(oldParent);
  96272. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96273. }
  96274. });
  96275. };
  96276. /**
  96277. * Detaches the behavior from the mesh
  96278. */
  96279. SixDofDragBehavior.prototype.detach = function () {
  96280. if (this._scene) {
  96281. this._scene.onPointerObservable.remove(this._pointerObserver);
  96282. }
  96283. if (this._ownerNode) {
  96284. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96285. }
  96286. if (this._virtualOriginMesh) {
  96287. this._virtualOriginMesh.dispose();
  96288. }
  96289. if (this._virtualDragMesh) {
  96290. this._virtualDragMesh.dispose();
  96291. }
  96292. this.onDragEndObservable.clear();
  96293. this.onDragStartObservable.clear();
  96294. };
  96295. return SixDofDragBehavior;
  96296. }());
  96297. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  96298. })(BABYLON || (BABYLON = {}));
  96299. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  96300. var BABYLON;
  96301. (function (BABYLON) {
  96302. /**
  96303. * @hidden
  96304. */
  96305. var FaceDirectionInfo = /** @class */ (function () {
  96306. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  96307. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  96308. if (diff === void 0) { diff = 0; }
  96309. if (ignore === void 0) { ignore = false; }
  96310. this.direction = direction;
  96311. this.rotatedDirection = rotatedDirection;
  96312. this.diff = diff;
  96313. this.ignore = ignore;
  96314. }
  96315. return FaceDirectionInfo;
  96316. }());
  96317. /**
  96318. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  96319. */
  96320. var AttachToBoxBehavior = /** @class */ (function () {
  96321. /**
  96322. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  96323. * @param ui The transform node that should be attched to the mesh
  96324. */
  96325. function AttachToBoxBehavior(ui) {
  96326. this.ui = ui;
  96327. /**
  96328. * The name of the behavior
  96329. */
  96330. this.name = "AttachToBoxBehavior";
  96331. /**
  96332. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  96333. */
  96334. this.distanceAwayFromFace = 0.15;
  96335. /**
  96336. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  96337. */
  96338. this.distanceAwayFromBottomOfFace = 0.15;
  96339. 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))];
  96340. this._tmpMatrix = new BABYLON.Matrix();
  96341. this._tmpVector = new BABYLON.Vector3();
  96342. this._zeroVector = BABYLON.Vector3.Zero();
  96343. this._lookAtTmpMatrix = new BABYLON.Matrix();
  96344. /* Does nothing */
  96345. }
  96346. /**
  96347. * Initializes the behavior
  96348. */
  96349. AttachToBoxBehavior.prototype.init = function () {
  96350. /* Does nothing */
  96351. };
  96352. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  96353. var _this = this;
  96354. // Go over each face and calculate the angle between the face's normal and targetDirection
  96355. this._faceVectors.forEach(function (v) {
  96356. if (!_this._target.rotationQuaternion) {
  96357. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  96358. }
  96359. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  96360. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  96361. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  96362. });
  96363. // Return the face information of the one with the normal closeset to target direction
  96364. return this._faceVectors.reduce(function (min, p) {
  96365. if (min.ignore) {
  96366. return p;
  96367. }
  96368. else if (p.ignore) {
  96369. return min;
  96370. }
  96371. else {
  96372. return min.diff < p.diff ? min : p;
  96373. }
  96374. }, this._faceVectors[0]);
  96375. };
  96376. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  96377. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  96378. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  96379. this._lookAtTmpMatrix.invert();
  96380. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  96381. };
  96382. /**
  96383. * Attaches the AttachToBoxBehavior to the passed in mesh
  96384. * @param target The mesh that the specified node will be attached to
  96385. */
  96386. AttachToBoxBehavior.prototype.attach = function (target) {
  96387. var _this = this;
  96388. this._target = target;
  96389. this._scene = this._target.getScene();
  96390. // Every frame, update the app bars position
  96391. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96392. if (!_this._scene.activeCamera) {
  96393. return;
  96394. }
  96395. // Find the face closest to the cameras position
  96396. var cameraPos = _this._scene.activeCamera.position;
  96397. if (_this._scene.activeCamera.devicePosition) {
  96398. cameraPos = _this._scene.activeCamera.devicePosition;
  96399. }
  96400. var facing = _this._closestFace(cameraPos.subtract(target.position));
  96401. if (_this._scene.activeCamera.leftCamera) {
  96402. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96403. }
  96404. else {
  96405. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96406. }
  96407. // Get camera up direction
  96408. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  96409. // Ignore faces to not select a parrelel face for the up vector of the UI
  96410. _this._faceVectors.forEach(function (v) {
  96411. if (facing.direction.x && v.direction.x) {
  96412. v.ignore = true;
  96413. }
  96414. if (facing.direction.y && v.direction.y) {
  96415. v.ignore = true;
  96416. }
  96417. if (facing.direction.z && v.direction.z) {
  96418. v.ignore = true;
  96419. }
  96420. });
  96421. var facingUp = _this._closestFace(_this._tmpVector);
  96422. // Unignore faces
  96423. _this._faceVectors.forEach(function (v) {
  96424. v.ignore = false;
  96425. });
  96426. // Position the app bar on that face
  96427. _this.ui.position.copyFrom(target.position);
  96428. if (facing.direction.x) {
  96429. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96430. _this.ui.position.addInPlace(_this._tmpVector);
  96431. }
  96432. if (facing.direction.y) {
  96433. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96434. _this.ui.position.addInPlace(_this._tmpVector);
  96435. }
  96436. if (facing.direction.z) {
  96437. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96438. _this.ui.position.addInPlace(_this._tmpVector);
  96439. }
  96440. // Rotate to be oriented properly to the camera
  96441. if (!_this.ui.rotationQuaternion) {
  96442. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  96443. }
  96444. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  96445. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  96446. // Place ui the correct distance from the bottom of the mesh
  96447. if (facingUp.direction.x) {
  96448. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  96449. }
  96450. if (facingUp.direction.y) {
  96451. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  96452. }
  96453. if (facingUp.direction.z) {
  96454. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  96455. }
  96456. _this.ui.position.addInPlace(_this._tmpVector);
  96457. });
  96458. };
  96459. /**
  96460. * Detaches the behavior from the mesh
  96461. */
  96462. AttachToBoxBehavior.prototype.detach = function () {
  96463. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  96464. };
  96465. return AttachToBoxBehavior;
  96466. }());
  96467. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  96468. })(BABYLON || (BABYLON = {}));
  96469. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  96470. var BABYLON;
  96471. (function (BABYLON) {
  96472. /**
  96473. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  96474. */
  96475. var FadeInOutBehavior = /** @class */ (function () {
  96476. /**
  96477. * Instatiates the FadeInOutBehavior
  96478. */
  96479. function FadeInOutBehavior() {
  96480. var _this = this;
  96481. /**
  96482. * Time in milliseconds to delay before fading in (Default: 0)
  96483. */
  96484. this.delay = 0;
  96485. /**
  96486. * Time in milliseconds for the mesh to fade in (Default: 300)
  96487. */
  96488. this.fadeInTime = 300;
  96489. this._millisecondsPerFrame = 1000 / 60;
  96490. this._hovered = false;
  96491. this._hoverValue = 0;
  96492. this._ownerNode = null;
  96493. this._update = function () {
  96494. if (_this._ownerNode) {
  96495. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  96496. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  96497. if (_this._ownerNode.visibility > 1) {
  96498. _this._setAllVisibility(_this._ownerNode, 1);
  96499. _this._hoverValue = _this.fadeInTime + _this.delay;
  96500. return;
  96501. }
  96502. else if (_this._ownerNode.visibility < 0) {
  96503. _this._setAllVisibility(_this._ownerNode, 0);
  96504. if (_this._hoverValue < 0) {
  96505. _this._hoverValue = 0;
  96506. return;
  96507. }
  96508. }
  96509. setTimeout(_this._update, _this._millisecondsPerFrame);
  96510. }
  96511. };
  96512. }
  96513. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  96514. /**
  96515. * The name of the behavior
  96516. */
  96517. get: function () {
  96518. return "FadeInOut";
  96519. },
  96520. enumerable: true,
  96521. configurable: true
  96522. });
  96523. /**
  96524. * Initializes the behavior
  96525. */
  96526. FadeInOutBehavior.prototype.init = function () {
  96527. };
  96528. /**
  96529. * Attaches the fade behavior on the passed in mesh
  96530. * @param ownerNode The mesh that will be faded in/out once attached
  96531. */
  96532. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  96533. this._ownerNode = ownerNode;
  96534. this._setAllVisibility(this._ownerNode, 0);
  96535. };
  96536. /**
  96537. * Detaches the behavior from the mesh
  96538. */
  96539. FadeInOutBehavior.prototype.detach = function () {
  96540. this._ownerNode = null;
  96541. };
  96542. /**
  96543. * Triggers the mesh to begin fading in or out
  96544. * @param value if the object should fade in or out (true to fade in)
  96545. */
  96546. FadeInOutBehavior.prototype.fadeIn = function (value) {
  96547. this._hovered = value;
  96548. this._update();
  96549. };
  96550. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  96551. var _this = this;
  96552. mesh.visibility = value;
  96553. mesh.getChildMeshes().forEach(function (c) {
  96554. _this._setAllVisibility(c, value);
  96555. });
  96556. };
  96557. return FadeInOutBehavior;
  96558. }());
  96559. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  96560. })(BABYLON || (BABYLON = {}));
  96561. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  96562. var BABYLON;
  96563. (function (BABYLON) {
  96564. /**
  96565. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  96566. */
  96567. var Gizmo = /** @class */ (function () {
  96568. /**
  96569. * Creates a gizmo
  96570. * @param gizmoLayer The utility layer the gizmo will be added to
  96571. */
  96572. function Gizmo(
  96573. /** The utility layer the gizmo will be added to */
  96574. gizmoLayer) {
  96575. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96576. var _this = this;
  96577. this.gizmoLayer = gizmoLayer;
  96578. /**
  96579. * Ratio for the scale of the gizmo (Default: 1)
  96580. */
  96581. this.scaleRatio = 1;
  96582. this._tmpMatrix = new BABYLON.Matrix();
  96583. /**
  96584. * If a custom mesh has been set (Default: false)
  96585. */
  96586. this._customMeshSet = false;
  96587. /**
  96588. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  96589. */
  96590. this.updateGizmoRotationToMatchAttachedMesh = true;
  96591. /**
  96592. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  96593. */
  96594. this.updateGizmoPositionToMatchAttachedMesh = true;
  96595. /**
  96596. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  96597. */
  96598. this._updateScale = true;
  96599. this._interactionsEnabled = true;
  96600. this._tempVector = new BABYLON.Vector3();
  96601. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  96602. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  96603. _this._update();
  96604. });
  96605. this.attachedMesh = null;
  96606. }
  96607. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  96608. /**
  96609. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  96610. * * When set, interactions will be enabled
  96611. */
  96612. get: function () {
  96613. return this._attachedMesh;
  96614. },
  96615. set: function (value) {
  96616. this._attachedMesh = value;
  96617. this._rootMesh.setEnabled(value ? true : false);
  96618. this._attachedMeshChanged(value);
  96619. },
  96620. enumerable: true,
  96621. configurable: true
  96622. });
  96623. /**
  96624. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96625. * @param mesh The mesh to replace the default mesh of the gizmo
  96626. */
  96627. Gizmo.prototype.setCustomMesh = function (mesh) {
  96628. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  96629. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  96630. }
  96631. this._rootMesh.getChildMeshes().forEach(function (c) {
  96632. c.dispose();
  96633. });
  96634. mesh.parent = this._rootMesh;
  96635. this._customMeshSet = true;
  96636. };
  96637. Gizmo.prototype._attachedMeshChanged = function (value) {
  96638. };
  96639. /**
  96640. * @hidden
  96641. * Updates the gizmo to match the attached mesh's position/rotation
  96642. */
  96643. Gizmo.prototype._update = function () {
  96644. if (this.attachedMesh) {
  96645. if (this.updateGizmoRotationToMatchAttachedMesh) {
  96646. if (!this._rootMesh.rotationQuaternion) {
  96647. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  96648. }
  96649. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  96650. this._tempVector.copyFrom(this.attachedMesh.scaling);
  96651. if (this.attachedMesh.scaling.x < 0) {
  96652. this.attachedMesh.scaling.x *= -1;
  96653. }
  96654. if (this.attachedMesh.scaling.y < 0) {
  96655. this.attachedMesh.scaling.y *= -1;
  96656. }
  96657. if (this.attachedMesh.scaling.z < 0) {
  96658. this.attachedMesh.scaling.z *= -1;
  96659. }
  96660. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  96661. this.attachedMesh.scaling.copyFrom(this._tempVector);
  96662. this.attachedMesh.computeWorldMatrix();
  96663. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  96664. }
  96665. else if (this._rootMesh.rotationQuaternion) {
  96666. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  96667. }
  96668. if (this.updateGizmoPositionToMatchAttachedMesh) {
  96669. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  96670. }
  96671. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  96672. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  96673. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  96674. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  96675. }
  96676. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  96677. var dist = this._tempVector.length() * this.scaleRatio;
  96678. this._rootMesh.scaling.set(dist, dist, dist);
  96679. }
  96680. }
  96681. };
  96682. /**
  96683. * Disposes of the gizmo
  96684. */
  96685. Gizmo.prototype.dispose = function () {
  96686. this._rootMesh.dispose();
  96687. if (this._beforeRenderObserver) {
  96688. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96689. }
  96690. };
  96691. return Gizmo;
  96692. }());
  96693. BABYLON.Gizmo = Gizmo;
  96694. })(BABYLON || (BABYLON = {}));
  96695. //# sourceMappingURL=babylon.gizmo.js.map
  96696. var BABYLON;
  96697. (function (BABYLON) {
  96698. /**
  96699. * Single axis drag gizmo
  96700. */
  96701. var AxisDragGizmo = /** @class */ (function (_super) {
  96702. __extends(AxisDragGizmo, _super);
  96703. /**
  96704. * Creates an AxisDragGizmo
  96705. * @param gizmoLayer The utility layer the gizmo will be added to
  96706. * @param dragAxis The axis which the gizmo will be able to drag on
  96707. * @param color The color of the gizmo
  96708. */
  96709. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  96710. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96711. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96712. var _this = _super.call(this, gizmoLayer) || this;
  96713. _this._pointerObserver = null;
  96714. /**
  96715. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96716. */
  96717. _this.snapDistance = 0;
  96718. /**
  96719. * Event that fires each time the gizmo snaps to a new location.
  96720. * * snapDistance is the the change in distance
  96721. */
  96722. _this.onSnapObservable = new BABYLON.Observable();
  96723. // Create Material
  96724. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96725. coloredMaterial.disableLighting = true;
  96726. coloredMaterial.emissiveColor = color;
  96727. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96728. hoverMaterial.disableLighting = true;
  96729. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96730. // Build mesh on root node
  96731. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96732. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  96733. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96734. arrowTail.color = coloredMaterial.emissiveColor;
  96735. arrow.addChild(arrowMesh);
  96736. arrow.addChild(arrowTail);
  96737. // Position arrow pointing in its drag axis
  96738. arrowMesh.scaling.scaleInPlace(0.05);
  96739. arrowMesh.material = coloredMaterial;
  96740. arrowMesh.rotation.x = Math.PI / 2;
  96741. arrowMesh.position.z += 0.3;
  96742. arrowTail.scaling.scaleInPlace(0.26);
  96743. arrowTail.rotation.x = Math.PI / 2;
  96744. arrowTail.material = coloredMaterial;
  96745. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96746. arrow.scaling.scaleInPlace(1 / 3);
  96747. _this._rootMesh.addChild(arrow);
  96748. var currentSnapDragDistance = 0;
  96749. var tmpVector = new BABYLON.Vector3();
  96750. var tmpSnapEvent = { snapDistance: 0 };
  96751. // Add drag behavior to handle events when the gizmo is dragged
  96752. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96753. _this.dragBehavior.moveAttached = false;
  96754. _this._rootMesh.addBehavior(_this.dragBehavior);
  96755. var localDelta = new BABYLON.Vector3();
  96756. var tmpMatrix = new BABYLON.Matrix();
  96757. _this.dragBehavior.onDragObservable.add(function (event) {
  96758. if (_this.attachedMesh) {
  96759. // Convert delta to local translation if it has a parent
  96760. if (_this.attachedMesh.parent) {
  96761. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96762. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  96763. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  96764. }
  96765. else {
  96766. localDelta.copyFrom(event.delta);
  96767. }
  96768. // Snapping logic
  96769. if (_this.snapDistance == 0) {
  96770. _this.attachedMesh.position.addInPlace(localDelta);
  96771. }
  96772. else {
  96773. currentSnapDragDistance += event.dragDistance;
  96774. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96775. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  96776. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96777. localDelta.normalizeToRef(tmpVector);
  96778. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  96779. _this.attachedMesh.position.addInPlace(tmpVector);
  96780. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96781. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96782. }
  96783. }
  96784. }
  96785. });
  96786. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96787. if (_this._customMeshSet) {
  96788. return;
  96789. }
  96790. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96791. var material = isHovered ? hoverMaterial : coloredMaterial;
  96792. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96793. m.material = material;
  96794. if (m.color) {
  96795. m.color = material.emissiveColor;
  96796. }
  96797. });
  96798. });
  96799. return _this;
  96800. }
  96801. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  96802. if (this.dragBehavior) {
  96803. this.dragBehavior.enabled = value ? true : false;
  96804. }
  96805. };
  96806. /**
  96807. * Disposes of the gizmo
  96808. */
  96809. AxisDragGizmo.prototype.dispose = function () {
  96810. this.onSnapObservable.clear();
  96811. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96812. this.dragBehavior.detach();
  96813. _super.prototype.dispose.call(this);
  96814. };
  96815. return AxisDragGizmo;
  96816. }(BABYLON.Gizmo));
  96817. BABYLON.AxisDragGizmo = AxisDragGizmo;
  96818. })(BABYLON || (BABYLON = {}));
  96819. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  96820. var BABYLON;
  96821. (function (BABYLON) {
  96822. /**
  96823. * Single axis scale gizmo
  96824. */
  96825. var AxisScaleGizmo = /** @class */ (function (_super) {
  96826. __extends(AxisScaleGizmo, _super);
  96827. /**
  96828. * Creates an AxisScaleGizmo
  96829. * @param gizmoLayer The utility layer the gizmo will be added to
  96830. * @param dragAxis The axis which the gizmo will be able to scale on
  96831. * @param color The color of the gizmo
  96832. */
  96833. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  96834. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96835. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96836. var _this = _super.call(this, gizmoLayer) || this;
  96837. _this._pointerObserver = null;
  96838. /**
  96839. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96840. */
  96841. _this.snapDistance = 0;
  96842. /**
  96843. * Event that fires each time the gizmo snaps to a new location.
  96844. * * snapDistance is the the change in distance
  96845. */
  96846. _this.onSnapObservable = new BABYLON.Observable();
  96847. /**
  96848. * If the scaling operation should be done on all axis (default: false)
  96849. */
  96850. _this.uniformScaling = false;
  96851. // Create Material
  96852. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96853. _this._coloredMaterial.disableLighting = true;
  96854. _this._coloredMaterial.emissiveColor = color;
  96855. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96856. hoverMaterial.disableLighting = true;
  96857. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96858. // Build mesh on root node
  96859. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96860. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  96861. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96862. arrowTail.color = _this._coloredMaterial.emissiveColor;
  96863. arrow.addChild(arrowMesh);
  96864. arrow.addChild(arrowTail);
  96865. // Position arrow pointing in its drag axis
  96866. arrowMesh.scaling.scaleInPlace(0.1);
  96867. arrowMesh.material = _this._coloredMaterial;
  96868. arrowMesh.rotation.x = Math.PI / 2;
  96869. arrowMesh.position.z += 0.3;
  96870. arrowTail.scaling.scaleInPlace(0.26);
  96871. arrowTail.rotation.x = Math.PI / 2;
  96872. arrowTail.material = _this._coloredMaterial;
  96873. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96874. _this._rootMesh.addChild(arrow);
  96875. arrow.scaling.scaleInPlace(1 / 3);
  96876. // Add drag behavior to handle events when the gizmo is dragged
  96877. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96878. _this.dragBehavior.moveAttached = false;
  96879. _this._rootMesh.addBehavior(_this.dragBehavior);
  96880. var currentSnapDragDistance = 0;
  96881. var tmpVector = new BABYLON.Vector3();
  96882. var tmpSnapEvent = { snapDistance: 0 };
  96883. _this.dragBehavior.onDragObservable.add(function (event) {
  96884. if (_this.attachedMesh) {
  96885. // Snapping logic
  96886. var snapped = false;
  96887. var dragSteps = 0;
  96888. if (_this.uniformScaling) {
  96889. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  96890. if (tmpVector.y < 0) {
  96891. tmpVector.scaleInPlace(-1);
  96892. }
  96893. }
  96894. else {
  96895. tmpVector.copyFrom(dragAxis);
  96896. }
  96897. if (_this.snapDistance == 0) {
  96898. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  96899. }
  96900. else {
  96901. currentSnapDragDistance += event.dragDistance;
  96902. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96903. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96904. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96905. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  96906. snapped = true;
  96907. }
  96908. else {
  96909. tmpVector.scaleInPlace(0);
  96910. }
  96911. }
  96912. _this.attachedMesh.scaling.addInPlace(tmpVector);
  96913. if (snapped) {
  96914. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96915. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96916. }
  96917. }
  96918. });
  96919. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96920. if (_this._customMeshSet) {
  96921. return;
  96922. }
  96923. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96924. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  96925. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96926. m.material = material;
  96927. if (m.color) {
  96928. m.color = material.emissiveColor;
  96929. }
  96930. });
  96931. });
  96932. return _this;
  96933. }
  96934. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  96935. if (this.dragBehavior) {
  96936. this.dragBehavior.enabled = value ? true : false;
  96937. }
  96938. };
  96939. /**
  96940. * Disposes of the gizmo
  96941. */
  96942. AxisScaleGizmo.prototype.dispose = function () {
  96943. this.onSnapObservable.clear();
  96944. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96945. this.dragBehavior.detach();
  96946. _super.prototype.dispose.call(this);
  96947. };
  96948. /**
  96949. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96950. * @param mesh The mesh to replace the default mesh of the gizmo
  96951. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  96952. */
  96953. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  96954. var _this = this;
  96955. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  96956. _super.prototype.setCustomMesh.call(this, mesh);
  96957. if (useGizmoMaterial) {
  96958. this._rootMesh.getChildMeshes().forEach(function (m) {
  96959. m.material = _this._coloredMaterial;
  96960. if (m.color) {
  96961. m.color = _this._coloredMaterial.emissiveColor;
  96962. }
  96963. });
  96964. this._customMeshSet = false;
  96965. }
  96966. };
  96967. return AxisScaleGizmo;
  96968. }(BABYLON.Gizmo));
  96969. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  96970. })(BABYLON || (BABYLON = {}));
  96971. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  96972. var BABYLON;
  96973. (function (BABYLON) {
  96974. /**
  96975. * Single plane rotation gizmo
  96976. */
  96977. var PlaneRotationGizmo = /** @class */ (function (_super) {
  96978. __extends(PlaneRotationGizmo, _super);
  96979. /**
  96980. * Creates a PlaneRotationGizmo
  96981. * @param gizmoLayer The utility layer the gizmo will be added to
  96982. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  96983. * @param color The color of the gizmo
  96984. */
  96985. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  96986. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96987. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96988. var _this = _super.call(this, gizmoLayer) || this;
  96989. _this._pointerObserver = null;
  96990. /**
  96991. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  96992. */
  96993. _this.snapDistance = 0;
  96994. /**
  96995. * Event that fires each time the gizmo snaps to a new location.
  96996. * * snapDistance is the the change in distance
  96997. */
  96998. _this.onSnapObservable = new BABYLON.Observable();
  96999. // Create Material
  97000. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97001. coloredMaterial.disableLighting = true;
  97002. coloredMaterial.emissiveColor = color;
  97003. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97004. hoverMaterial.disableLighting = true;
  97005. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97006. // Build mesh on root node
  97007. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97008. // Create circle out of lines
  97009. var tessellation = 20;
  97010. var radius = 0.8;
  97011. var points = new Array();
  97012. for (var i = 0; i < tessellation; i++) {
  97013. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  97014. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  97015. }
  97016. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  97017. rotationMesh.color = coloredMaterial.emissiveColor;
  97018. // Position arrow pointing in its drag axis
  97019. rotationMesh.scaling.scaleInPlace(0.26);
  97020. rotationMesh.material = coloredMaterial;
  97021. rotationMesh.rotation.x = Math.PI / 2;
  97022. parentMesh.addChild(rotationMesh);
  97023. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  97024. _this._rootMesh.addChild(parentMesh);
  97025. parentMesh.scaling.scaleInPlace(1 / 3);
  97026. // Add drag behavior to handle events when the gizmo is dragged
  97027. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  97028. _this.dragBehavior.moveAttached = false;
  97029. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  97030. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  97031. _this._rootMesh.addBehavior(_this.dragBehavior);
  97032. var lastDragPosition = new BABYLON.Vector3();
  97033. _this.dragBehavior.onDragStartObservable.add(function (e) {
  97034. if (_this.attachedMesh) {
  97035. lastDragPosition.copyFrom(e.dragPlanePoint);
  97036. }
  97037. });
  97038. var rotationMatrix = new BABYLON.Matrix();
  97039. var planeNormalTowardsCamera = new BABYLON.Vector3();
  97040. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  97041. var tmpSnapEvent = { snapDistance: 0 };
  97042. var currentSnapDragDistance = 0;
  97043. var tmpMatrix = new BABYLON.Matrix();
  97044. var tmpVector = new BABYLON.Vector3();
  97045. var amountToRotate = new BABYLON.Quaternion();
  97046. _this.dragBehavior.onDragObservable.add(function (event) {
  97047. if (_this.attachedMesh) {
  97048. if (!_this.attachedMesh.rotationQuaternion) {
  97049. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97050. }
  97051. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  97052. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  97053. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  97054. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  97055. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  97056. var angle = Math.atan2(cross.length(), dot);
  97057. planeNormalTowardsCamera.copyFrom(planeNormal);
  97058. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  97059. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97060. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  97061. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  97062. }
  97063. // Flip up vector depending on which side the camera is on
  97064. if (gizmoLayer.utilityLayerScene.activeCamera) {
  97065. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  97066. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  97067. planeNormalTowardsCamera.scaleInPlace(-1);
  97068. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  97069. }
  97070. }
  97071. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  97072. if (halfCircleSide)
  97073. angle = -angle;
  97074. // Snapping logic
  97075. var snapped = false;
  97076. if (_this.snapDistance != 0) {
  97077. currentSnapDragDistance += angle;
  97078. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97079. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97080. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97081. angle = _this.snapDistance * dragSteps;
  97082. snapped = true;
  97083. }
  97084. else {
  97085. angle = 0;
  97086. }
  97087. }
  97088. // If the mesh has a parent, convert needed world rotation to local rotation
  97089. tmpMatrix.reset();
  97090. if (_this.attachedMesh.parent) {
  97091. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97092. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  97093. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  97094. }
  97095. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  97096. var quaternionCoefficient = Math.sin(angle / 2);
  97097. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  97098. // 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
  97099. if (tmpMatrix.determinant() > 0) {
  97100. amountToRotate.toEulerAnglesToRef(tmpVector);
  97101. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  97102. }
  97103. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97104. // Rotate selected mesh quaternion over fixed axis
  97105. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  97106. }
  97107. else {
  97108. // Rotate selected mesh quaternion over rotated axis
  97109. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  97110. }
  97111. lastDragPosition.copyFrom(event.dragPlanePoint);
  97112. if (snapped) {
  97113. tmpSnapEvent.snapDistance = angle;
  97114. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97115. }
  97116. }
  97117. });
  97118. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97119. if (_this._customMeshSet) {
  97120. return;
  97121. }
  97122. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97123. var material = isHovered ? hoverMaterial : coloredMaterial;
  97124. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97125. m.material = material;
  97126. if (m.color) {
  97127. m.color = material.emissiveColor;
  97128. }
  97129. });
  97130. });
  97131. return _this;
  97132. }
  97133. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  97134. if (this.dragBehavior) {
  97135. this.dragBehavior.enabled = value ? true : false;
  97136. }
  97137. };
  97138. /**
  97139. * Disposes of the gizmo
  97140. */
  97141. PlaneRotationGizmo.prototype.dispose = function () {
  97142. this.onSnapObservable.clear();
  97143. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97144. this.dragBehavior.detach();
  97145. _super.prototype.dispose.call(this);
  97146. };
  97147. return PlaneRotationGizmo;
  97148. }(BABYLON.Gizmo));
  97149. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  97150. })(BABYLON || (BABYLON = {}));
  97151. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  97152. var BABYLON;
  97153. (function (BABYLON) {
  97154. /**
  97155. * Gizmo that enables dragging a mesh along 3 axis
  97156. */
  97157. var PositionGizmo = /** @class */ (function (_super) {
  97158. __extends(PositionGizmo, _super);
  97159. /**
  97160. * Creates a PositionGizmo
  97161. * @param gizmoLayer The utility layer the gizmo will be added to
  97162. */
  97163. function PositionGizmo(gizmoLayer) {
  97164. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97165. var _this = _super.call(this, gizmoLayer) || this;
  97166. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97167. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97168. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97169. _this.attachedMesh = null;
  97170. return _this;
  97171. }
  97172. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  97173. set: function (mesh) {
  97174. if (this.xGizmo) {
  97175. this.xGizmo.attachedMesh = mesh;
  97176. this.yGizmo.attachedMesh = mesh;
  97177. this.zGizmo.attachedMesh = mesh;
  97178. }
  97179. },
  97180. enumerable: true,
  97181. configurable: true
  97182. });
  97183. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97184. get: function () {
  97185. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97186. },
  97187. set: function (value) {
  97188. if (this.xGizmo) {
  97189. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97190. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97191. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97192. }
  97193. },
  97194. enumerable: true,
  97195. configurable: true
  97196. });
  97197. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  97198. get: function () {
  97199. return this.xGizmo.snapDistance;
  97200. },
  97201. /**
  97202. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97203. */
  97204. set: function (value) {
  97205. if (this.xGizmo) {
  97206. this.xGizmo.snapDistance = value;
  97207. this.yGizmo.snapDistance = value;
  97208. this.zGizmo.snapDistance = value;
  97209. }
  97210. },
  97211. enumerable: true,
  97212. configurable: true
  97213. });
  97214. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  97215. get: function () {
  97216. return this.xGizmo.scaleRatio;
  97217. },
  97218. /**
  97219. * Ratio for the scale of the gizmo (Default: 1)
  97220. */
  97221. set: function (value) {
  97222. if (this.xGizmo) {
  97223. this.xGizmo.scaleRatio = value;
  97224. this.yGizmo.scaleRatio = value;
  97225. this.zGizmo.scaleRatio = value;
  97226. }
  97227. },
  97228. enumerable: true,
  97229. configurable: true
  97230. });
  97231. /**
  97232. * Disposes of the gizmo
  97233. */
  97234. PositionGizmo.prototype.dispose = function () {
  97235. this.xGizmo.dispose();
  97236. this.yGizmo.dispose();
  97237. this.zGizmo.dispose();
  97238. };
  97239. /**
  97240. * CustomMeshes are not supported by this gizmo
  97241. * @param mesh The mesh to replace the default mesh of the gizmo
  97242. */
  97243. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  97244. 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)");
  97245. };
  97246. return PositionGizmo;
  97247. }(BABYLON.Gizmo));
  97248. BABYLON.PositionGizmo = PositionGizmo;
  97249. })(BABYLON || (BABYLON = {}));
  97250. //# sourceMappingURL=babylon.positionGizmo.js.map
  97251. var BABYLON;
  97252. (function (BABYLON) {
  97253. /**
  97254. * Gizmo that enables rotating a mesh along 3 axis
  97255. */
  97256. var RotationGizmo = /** @class */ (function (_super) {
  97257. __extends(RotationGizmo, _super);
  97258. /**
  97259. * Creates a RotationGizmo
  97260. * @param gizmoLayer The utility layer the gizmo will be added to
  97261. */
  97262. function RotationGizmo(gizmoLayer) {
  97263. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97264. var _this = _super.call(this, gizmoLayer) || this;
  97265. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97266. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97267. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97268. _this.attachedMesh = null;
  97269. return _this;
  97270. }
  97271. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  97272. set: function (mesh) {
  97273. if (this.xGizmo) {
  97274. this.xGizmo.attachedMesh = mesh;
  97275. this.yGizmo.attachedMesh = mesh;
  97276. this.zGizmo.attachedMesh = mesh;
  97277. }
  97278. },
  97279. enumerable: true,
  97280. configurable: true
  97281. });
  97282. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97283. get: function () {
  97284. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97285. },
  97286. set: function (value) {
  97287. if (this.xGizmo) {
  97288. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97289. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97290. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97291. }
  97292. },
  97293. enumerable: true,
  97294. configurable: true
  97295. });
  97296. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  97297. get: function () {
  97298. return this.xGizmo.snapDistance;
  97299. },
  97300. /**
  97301. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97302. */
  97303. set: function (value) {
  97304. if (this.xGizmo) {
  97305. this.xGizmo.snapDistance = value;
  97306. this.yGizmo.snapDistance = value;
  97307. this.zGizmo.snapDistance = value;
  97308. }
  97309. },
  97310. enumerable: true,
  97311. configurable: true
  97312. });
  97313. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  97314. get: function () {
  97315. return this.xGizmo.scaleRatio;
  97316. },
  97317. /**
  97318. * Ratio for the scale of the gizmo (Default: 1)
  97319. */
  97320. set: function (value) {
  97321. if (this.xGizmo) {
  97322. this.xGizmo.scaleRatio = value;
  97323. this.yGizmo.scaleRatio = value;
  97324. this.zGizmo.scaleRatio = value;
  97325. }
  97326. },
  97327. enumerable: true,
  97328. configurable: true
  97329. });
  97330. /**
  97331. * Disposes of the gizmo
  97332. */
  97333. RotationGizmo.prototype.dispose = function () {
  97334. this.xGizmo.dispose();
  97335. this.yGizmo.dispose();
  97336. this.zGizmo.dispose();
  97337. };
  97338. /**
  97339. * CustomMeshes are not supported by this gizmo
  97340. * @param mesh The mesh to replace the default mesh of the gizmo
  97341. */
  97342. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  97343. 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)");
  97344. };
  97345. return RotationGizmo;
  97346. }(BABYLON.Gizmo));
  97347. BABYLON.RotationGizmo = RotationGizmo;
  97348. })(BABYLON || (BABYLON = {}));
  97349. //# sourceMappingURL=babylon.rotationGizmo.js.map
  97350. var BABYLON;
  97351. (function (BABYLON) {
  97352. /**
  97353. * Gizmo that enables scaling a mesh along 3 axis
  97354. */
  97355. var ScaleGizmo = /** @class */ (function (_super) {
  97356. __extends(ScaleGizmo, _super);
  97357. /**
  97358. * Creates a ScaleGizmo
  97359. * @param gizmoLayer The utility layer the gizmo will be added to
  97360. */
  97361. function ScaleGizmo(gizmoLayer) {
  97362. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97363. var _this = _super.call(this, gizmoLayer) || this;
  97364. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97365. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97366. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97367. // Create uniform scale gizmo
  97368. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  97369. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97370. _this.uniformScaleGizmo.uniformScaling = true;
  97371. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  97372. octahedron.scaling.scaleInPlace(0.007);
  97373. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  97374. _this.attachedMesh = null;
  97375. return _this;
  97376. }
  97377. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  97378. set: function (mesh) {
  97379. if (this.xGizmo) {
  97380. this.xGizmo.attachedMesh = mesh;
  97381. this.yGizmo.attachedMesh = mesh;
  97382. this.zGizmo.attachedMesh = mesh;
  97383. this.uniformScaleGizmo.attachedMesh = mesh;
  97384. }
  97385. },
  97386. enumerable: true,
  97387. configurable: true
  97388. });
  97389. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97390. get: function () {
  97391. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97392. },
  97393. set: function (value) {
  97394. if (this.xGizmo) {
  97395. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97396. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97397. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97398. }
  97399. },
  97400. enumerable: true,
  97401. configurable: true
  97402. });
  97403. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  97404. get: function () {
  97405. return this.xGizmo.snapDistance;
  97406. },
  97407. /**
  97408. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97409. */
  97410. set: function (value) {
  97411. if (this.xGizmo) {
  97412. this.xGizmo.snapDistance = value;
  97413. this.yGizmo.snapDistance = value;
  97414. this.zGizmo.snapDistance = value;
  97415. this.uniformScaleGizmo.snapDistance = value;
  97416. }
  97417. },
  97418. enumerable: true,
  97419. configurable: true
  97420. });
  97421. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  97422. get: function () {
  97423. return this.xGizmo.scaleRatio;
  97424. },
  97425. /**
  97426. * Ratio for the scale of the gizmo (Default: 1)
  97427. */
  97428. set: function (value) {
  97429. if (this.xGizmo) {
  97430. this.xGizmo.scaleRatio = value;
  97431. this.yGizmo.scaleRatio = value;
  97432. this.zGizmo.scaleRatio = value;
  97433. this.uniformScaleGizmo.scaleRatio = value;
  97434. }
  97435. },
  97436. enumerable: true,
  97437. configurable: true
  97438. });
  97439. /**
  97440. * Disposes of the gizmo
  97441. */
  97442. ScaleGizmo.prototype.dispose = function () {
  97443. this.xGizmo.dispose();
  97444. this.yGizmo.dispose();
  97445. this.zGizmo.dispose();
  97446. this.uniformScaleGizmo.dispose();
  97447. };
  97448. return ScaleGizmo;
  97449. }(BABYLON.Gizmo));
  97450. BABYLON.ScaleGizmo = ScaleGizmo;
  97451. })(BABYLON || (BABYLON = {}));
  97452. //# sourceMappingURL=babylon.scaleGizmo.js.map
  97453. var BABYLON;
  97454. (function (BABYLON) {
  97455. /**
  97456. * Bounding box gizmo
  97457. */
  97458. var BoundingBoxGizmo = /** @class */ (function (_super) {
  97459. __extends(BoundingBoxGizmo, _super);
  97460. /**
  97461. * Creates an BoundingBoxGizmo
  97462. * @param gizmoLayer The utility layer the gizmo will be added to
  97463. * @param color The color of the gizmo
  97464. */
  97465. function BoundingBoxGizmo(color, gizmoLayer) {
  97466. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97467. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  97468. var _this = _super.call(this, gizmoLayer) || this;
  97469. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  97470. _this._renderObserver = null;
  97471. _this._pointerObserver = null;
  97472. _this._scaleDragSpeed = 0.2;
  97473. _this._tmpQuaternion = new BABYLON.Quaternion();
  97474. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97475. _this._tmpRotationMatrix = new BABYLON.Matrix();
  97476. /**
  97477. * 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)
  97478. */
  97479. _this.ignoreChildren = false;
  97480. /**
  97481. * 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)
  97482. */
  97483. _this.includeChildPredicate = null;
  97484. /**
  97485. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  97486. */
  97487. _this.rotationSphereSize = 0.1;
  97488. /**
  97489. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  97490. */
  97491. _this.scaleBoxSize = 0.1;
  97492. /**
  97493. * 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)
  97494. */
  97495. _this.fixedDragMeshScreenSize = false;
  97496. /**
  97497. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  97498. */
  97499. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  97500. /**
  97501. * Fired when a rotation sphere or scale box is dragged
  97502. */
  97503. _this.onDragStartObservable = new BABYLON.Observable();
  97504. /**
  97505. * Fired when a scale box is dragged
  97506. */
  97507. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  97508. /**
  97509. * Fired when a scale box drag is ended
  97510. */
  97511. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  97512. /**
  97513. * Fired when a rotation sphere is dragged
  97514. */
  97515. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  97516. /**
  97517. * Fired when a rotation sphere drag is ended
  97518. */
  97519. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  97520. /**
  97521. * 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)
  97522. */
  97523. _this.scalePivot = null;
  97524. _this._existingMeshScale = new BABYLON.Vector3();
  97525. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  97526. _this._updateScale = false;
  97527. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  97528. // Create Materials
  97529. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97530. coloredMaterial.disableLighting = true;
  97531. coloredMaterial.emissiveColor = color;
  97532. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97533. hoverColoredMaterial.disableLighting = true;
  97534. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97535. // Build bounding box out of lines
  97536. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97537. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  97538. var lines = [];
  97539. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  97540. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  97541. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  97542. 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));
  97543. 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));
  97544. 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));
  97545. 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));
  97546. 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));
  97547. 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));
  97548. 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));
  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, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  97550. 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));
  97551. lines.forEach(function (l) {
  97552. l.color = color;
  97553. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  97554. l.isPickable = false;
  97555. _this._lineBoundingBox.addChild(l);
  97556. });
  97557. _this._rootMesh.addChild(_this._lineBoundingBox);
  97558. // Create rotation spheres
  97559. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97560. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  97561. var _loop_1 = function (i_1) {
  97562. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  97563. sphere.rotationQuaternion = new BABYLON.Quaternion();
  97564. sphere.material = coloredMaterial;
  97565. // Drag behavior
  97566. _dragBehavior = new BABYLON.PointerDragBehavior({});
  97567. _dragBehavior.moveAttached = false;
  97568. _dragBehavior.updateDragPlane = false;
  97569. sphere.addBehavior(_dragBehavior);
  97570. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  97571. var totalTurnAmountOfDrag = 0;
  97572. _dragBehavior.onDragStartObservable.add(function (event) {
  97573. startingTurnDirection.copyFrom(sphere.forward);
  97574. totalTurnAmountOfDrag = 0;
  97575. });
  97576. _dragBehavior.onDragObservable.add(function (event) {
  97577. _this.onRotationSphereDragObservable.notifyObservers({});
  97578. if (_this.attachedMesh) {
  97579. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97580. var worldDragDirection = startingTurnDirection;
  97581. // Project the world right on to the drag plane
  97582. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  97583. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  97584. // project drag delta on to the resulting drag axis and rotate based on that
  97585. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  97586. // Make rotation relative to size of mesh.
  97587. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97588. // Rotate based on axis
  97589. if (!_this.attachedMesh.rotationQuaternion) {
  97590. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97591. }
  97592. if (!_this._anchorMesh.rotationQuaternion) {
  97593. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  97594. }
  97595. // Do not allow the object to turn more than a full circle
  97596. totalTurnAmountOfDrag += projectDist;
  97597. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  97598. if (i_1 >= 8) {
  97599. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  97600. }
  97601. else if (i_1 >= 4) {
  97602. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  97603. }
  97604. else {
  97605. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  97606. }
  97607. // Rotate around center of bounding box
  97608. _this._anchorMesh.addChild(_this.attachedMesh);
  97609. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  97610. _this._anchorMesh.removeChild(_this.attachedMesh);
  97611. }
  97612. _this.updateBoundingBox();
  97613. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97614. }
  97615. });
  97616. // Selection/deselection
  97617. _dragBehavior.onDragStartObservable.add(function () {
  97618. _this.onDragStartObservable.notifyObservers({});
  97619. _this._selectNode(sphere);
  97620. });
  97621. _dragBehavior.onDragEndObservable.add(function () {
  97622. _this.onRotationSphereDragEndObservable.notifyObservers({});
  97623. _this._selectNode(null);
  97624. });
  97625. this_1._rotateSpheresParent.addChild(sphere);
  97626. };
  97627. var this_1 = this, _dragBehavior;
  97628. for (var i_1 = 0; i_1 < 12; i_1++) {
  97629. _loop_1(i_1);
  97630. }
  97631. _this._rootMesh.addChild(_this._rotateSpheresParent);
  97632. // Create scale cubes
  97633. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97634. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  97635. for (var i = 0; i < 2; i++) {
  97636. for (var j = 0; j < 2; j++) {
  97637. var _loop_2 = function () {
  97638. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  97639. box.material = coloredMaterial;
  97640. // Dragging logic
  97641. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  97642. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97643. _dragBehavior.moveAttached = false;
  97644. box.addBehavior(_dragBehavior);
  97645. _dragBehavior.onDragObservable.add(function (event) {
  97646. _this.onScaleBoxDragObservable.notifyObservers({});
  97647. if (_this.attachedMesh) {
  97648. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97649. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97650. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  97651. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  97652. _this.updateBoundingBox();
  97653. if (_this.scalePivot) {
  97654. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  97655. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  97656. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  97657. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97658. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97659. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  97660. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97661. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  97662. }
  97663. else {
  97664. // Scale from the position of the opposite corner
  97665. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  97666. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97667. }
  97668. _this._anchorMesh.addChild(_this.attachedMesh);
  97669. _this._anchorMesh.scaling.addInPlace(deltaScale);
  97670. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  97671. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  97672. }
  97673. _this._anchorMesh.removeChild(_this.attachedMesh);
  97674. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97675. }
  97676. });
  97677. // Selection/deselection
  97678. _dragBehavior.onDragStartObservable.add(function () {
  97679. _this.onDragStartObservable.notifyObservers({});
  97680. _this._selectNode(box);
  97681. });
  97682. _dragBehavior.onDragEndObservable.add(function () {
  97683. _this.onScaleBoxDragEndObservable.notifyObservers({});
  97684. _this._selectNode(null);
  97685. });
  97686. this_2._scaleBoxesParent.addChild(box);
  97687. };
  97688. var this_2 = this, _dragBehavior;
  97689. for (var k = 0; k < 2; k++) {
  97690. _loop_2();
  97691. }
  97692. }
  97693. }
  97694. _this._rootMesh.addChild(_this._scaleBoxesParent);
  97695. // Hover color change
  97696. var pointerIds = new Array();
  97697. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97698. if (!pointerIds[pointerInfo.event.pointerId]) {
  97699. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  97700. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  97701. pointerIds[pointerInfo.event.pointerId] = mesh;
  97702. mesh.material = hoverColoredMaterial;
  97703. }
  97704. });
  97705. }
  97706. else {
  97707. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  97708. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  97709. delete pointerIds[pointerInfo.event.pointerId];
  97710. }
  97711. }
  97712. });
  97713. // Update bounding box positions
  97714. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  97715. // Only update the bouding box if scaling has changed
  97716. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  97717. _this.updateBoundingBox();
  97718. }
  97719. });
  97720. _this.updateBoundingBox();
  97721. return _this;
  97722. }
  97723. /** @hidden */
  97724. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  97725. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  97726. // Save old pivot and set pivot to 0,0,0
  97727. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  97728. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  97729. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  97730. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  97731. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97732. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97733. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97734. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  97735. }
  97736. }
  97737. BoundingBoxGizmo._PivotCached++;
  97738. };
  97739. /** @hidden */
  97740. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  97741. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  97742. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  97743. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97744. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97745. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97746. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  97747. }
  97748. this._PivotCached--;
  97749. };
  97750. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  97751. if (value) {
  97752. // Reset anchor mesh to match attached mesh's scale
  97753. // This is needed to avoid invalid box/sphere position on first drag
  97754. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  97755. this._anchorMesh.addChild(value);
  97756. this._anchorMesh.removeChild(value);
  97757. BoundingBoxGizmo._RestorePivotPoint(value);
  97758. this.updateBoundingBox();
  97759. }
  97760. };
  97761. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  97762. this._rotateSpheresParent.getChildMeshes()
  97763. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  97764. m.isVisible = (!selectedMesh || m == selectedMesh);
  97765. });
  97766. };
  97767. /**
  97768. * Updates the bounding box information for the Gizmo
  97769. */
  97770. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  97771. if (this.attachedMesh) {
  97772. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  97773. this._update();
  97774. // Rotate based on axis
  97775. if (!this.attachedMesh.rotationQuaternion) {
  97776. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  97777. }
  97778. if (!this._anchorMesh.rotationQuaternion) {
  97779. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  97780. }
  97781. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97782. // Store original position and reset mesh to origin before computing the bounding box
  97783. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97784. this._tmpVector.copyFrom(this.attachedMesh.position);
  97785. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  97786. this.attachedMesh.position.set(0, 0, 0);
  97787. // Update bounding dimensions/positions
  97788. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  97789. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  97790. // Update gizmo to match bounding box scaling and rotation
  97791. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  97792. 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);
  97793. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  97794. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  97795. this._lineBoundingBox.computeWorldMatrix();
  97796. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  97797. // restore position/rotation values
  97798. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  97799. this.attachedMesh.position.copyFrom(this._tmpVector);
  97800. }
  97801. // Update rotation sphere locations
  97802. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  97803. for (var i = 0; i < 3; i++) {
  97804. for (var j = 0; j < 2; j++) {
  97805. for (var k = 0; k < 2; k++) {
  97806. var index = ((i * 4) + (j * 2)) + k;
  97807. if (i == 0) {
  97808. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97809. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97810. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97811. }
  97812. if (i == 1) {
  97813. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  97814. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97815. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97816. }
  97817. if (i == 2) {
  97818. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  97819. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97820. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97821. }
  97822. if (this.fixedDragMeshScreenSize) {
  97823. this._rootMesh.computeWorldMatrix();
  97824. this._rotateSpheresParent.computeWorldMatrix();
  97825. rotateSpheres[index].computeWorldMatrix();
  97826. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97827. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97828. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97829. }
  97830. else {
  97831. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  97832. }
  97833. }
  97834. }
  97835. }
  97836. // Update scale box locations
  97837. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  97838. for (var i = 0; i < 2; i++) {
  97839. for (var j = 0; j < 2; j++) {
  97840. for (var k = 0; k < 2; k++) {
  97841. var index = ((i * 4) + (j * 2)) + k;
  97842. if (scaleBoxes[index]) {
  97843. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97844. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97845. if (this.fixedDragMeshScreenSize) {
  97846. this._rootMesh.computeWorldMatrix();
  97847. this._scaleBoxesParent.computeWorldMatrix();
  97848. scaleBoxes[index].computeWorldMatrix();
  97849. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97850. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97851. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97852. }
  97853. else {
  97854. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  97855. }
  97856. }
  97857. }
  97858. }
  97859. }
  97860. if (this.attachedMesh) {
  97861. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  97862. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  97863. }
  97864. };
  97865. /**
  97866. * Enables rotation on the specified axis and disables rotation on the others
  97867. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  97868. */
  97869. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  97870. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  97871. if (i < 4) {
  97872. m.setEnabled(axis.indexOf("x") != -1);
  97873. }
  97874. else if (i < 8) {
  97875. m.setEnabled(axis.indexOf("y") != -1);
  97876. }
  97877. else {
  97878. m.setEnabled(axis.indexOf("z") != -1);
  97879. }
  97880. });
  97881. };
  97882. /**
  97883. * Disposes of the gizmo
  97884. */
  97885. BoundingBoxGizmo.prototype.dispose = function () {
  97886. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97887. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  97888. this._lineBoundingBox.dispose();
  97889. this._rotateSpheresParent.dispose();
  97890. this._scaleBoxesParent.dispose();
  97891. _super.prototype.dispose.call(this);
  97892. };
  97893. /**
  97894. * 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)
  97895. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  97896. * @returns the bounding box mesh with the passed in mesh as a child
  97897. */
  97898. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  97899. var makeNotPickable = function (root) {
  97900. root.isPickable = false;
  97901. root.getChildMeshes().forEach(function (c) {
  97902. makeNotPickable(c);
  97903. });
  97904. };
  97905. makeNotPickable(mesh);
  97906. // Reset position to get boudning box from origin with no rotation
  97907. if (!mesh.rotationQuaternion) {
  97908. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  97909. }
  97910. var oldPos = mesh.position.clone();
  97911. var oldRot = mesh.rotationQuaternion.clone();
  97912. mesh.rotationQuaternion.set(0, 0, 0, 1);
  97913. mesh.position.set(0, 0, 0);
  97914. // Update bounding dimensions/positions
  97915. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  97916. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  97917. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  97918. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97919. // Restore original positions
  97920. mesh.addChild(box);
  97921. mesh.rotationQuaternion.copyFrom(oldRot);
  97922. mesh.position.copyFrom(oldPos);
  97923. // Reverse parenting
  97924. mesh.removeChild(box);
  97925. box.addChild(mesh);
  97926. box.visibility = 0;
  97927. return box;
  97928. };
  97929. /**
  97930. * CustomMeshes are not supported by this gizmo
  97931. * @param mesh The mesh to replace the default mesh of the gizmo
  97932. */
  97933. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  97934. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  97935. };
  97936. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  97937. // store/remove pivot point should only be applied during their outermost calls
  97938. BoundingBoxGizmo._PivotCached = 0;
  97939. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  97940. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  97941. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  97942. return BoundingBoxGizmo;
  97943. }(BABYLON.Gizmo));
  97944. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  97945. })(BABYLON || (BABYLON = {}));
  97946. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  97947. var BABYLON;
  97948. (function (BABYLON) {
  97949. /**
  97950. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  97951. */
  97952. var GizmoManager = /** @class */ (function () {
  97953. /**
  97954. * Instatiates a gizmo manager
  97955. * @param scene the scene to overlay the gizmos on top of
  97956. */
  97957. function GizmoManager(scene) {
  97958. var _this = this;
  97959. this.scene = scene;
  97960. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  97961. this._pointerObserver = null;
  97962. this._attachedMesh = null;
  97963. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  97964. /**
  97965. * When bounding box gizmo is enabled, this can be used to track drag/end events
  97966. */
  97967. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  97968. /**
  97969. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  97970. */
  97971. this.attachableMeshes = null;
  97972. /**
  97973. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  97974. */
  97975. this.usePointerToAttachGizmos = true;
  97976. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  97977. // Instatiate/dispose gizmos based on pointer actions
  97978. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  97979. if (!_this.usePointerToAttachGizmos) {
  97980. return;
  97981. }
  97982. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97983. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  97984. var node = pointerInfo.pickInfo.pickedMesh;
  97985. if (_this.attachableMeshes == null) {
  97986. // Attach to the most parent node
  97987. while (node && node.parent != null) {
  97988. node = node.parent;
  97989. }
  97990. }
  97991. else {
  97992. // Attach to the parent node that is an attachableMesh
  97993. var found = false;
  97994. _this.attachableMeshes.forEach(function (mesh) {
  97995. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  97996. node = mesh;
  97997. found = true;
  97998. }
  97999. });
  98000. if (!found) {
  98001. node = null;
  98002. }
  98003. }
  98004. if (node instanceof BABYLON.AbstractMesh) {
  98005. _this.attachToMesh(node);
  98006. }
  98007. else {
  98008. _this.attachToMesh(null);
  98009. }
  98010. }
  98011. else {
  98012. _this.attachToMesh(null);
  98013. }
  98014. }
  98015. });
  98016. }
  98017. /**
  98018. * Attaches a set of gizmos to the specified mesh
  98019. * @param mesh The mesh the gizmo's should be attached to
  98020. */
  98021. GizmoManager.prototype.attachToMesh = function (mesh) {
  98022. if (this._attachedMesh) {
  98023. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98024. }
  98025. this._attachedMesh = mesh;
  98026. for (var key in this.gizmos) {
  98027. var gizmo = (this.gizmos[key]);
  98028. if (gizmo && this._gizmosEnabled[key]) {
  98029. gizmo.attachedMesh = mesh;
  98030. }
  98031. }
  98032. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  98033. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98034. }
  98035. };
  98036. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  98037. get: function () {
  98038. return this._gizmosEnabled.positionGizmo;
  98039. },
  98040. /**
  98041. * If the position gizmo is enabled
  98042. */
  98043. set: function (value) {
  98044. if (value) {
  98045. if (!this.gizmos.positionGizmo) {
  98046. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  98047. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98048. }
  98049. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  98050. }
  98051. else if (this.gizmos.positionGizmo) {
  98052. this.gizmos.positionGizmo.attachedMesh = null;
  98053. }
  98054. this._gizmosEnabled.positionGizmo = value;
  98055. },
  98056. enumerable: true,
  98057. configurable: true
  98058. });
  98059. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  98060. get: function () {
  98061. return this._gizmosEnabled.rotationGizmo;
  98062. },
  98063. /**
  98064. * If the rotation gizmo is enabled
  98065. */
  98066. set: function (value) {
  98067. if (value) {
  98068. if (!this.gizmos.rotationGizmo) {
  98069. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  98070. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98071. }
  98072. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  98073. }
  98074. else if (this.gizmos.rotationGizmo) {
  98075. this.gizmos.rotationGizmo.attachedMesh = null;
  98076. }
  98077. this._gizmosEnabled.rotationGizmo = value;
  98078. },
  98079. enumerable: true,
  98080. configurable: true
  98081. });
  98082. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  98083. get: function () {
  98084. return this._gizmosEnabled.scaleGizmo;
  98085. },
  98086. /**
  98087. * If the scale gizmo is enabled
  98088. */
  98089. set: function (value) {
  98090. if (value) {
  98091. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  98092. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  98093. }
  98094. else if (this.gizmos.scaleGizmo) {
  98095. this.gizmos.scaleGizmo.attachedMesh = null;
  98096. }
  98097. this._gizmosEnabled.scaleGizmo = value;
  98098. },
  98099. enumerable: true,
  98100. configurable: true
  98101. });
  98102. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  98103. get: function () {
  98104. return this._gizmosEnabled.boundingBoxGizmo;
  98105. },
  98106. /**
  98107. * If the boundingBox gizmo is enabled
  98108. */
  98109. set: function (value) {
  98110. if (value) {
  98111. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  98112. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  98113. if (this._attachedMesh) {
  98114. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98115. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98116. }
  98117. }
  98118. else if (this.gizmos.boundingBoxGizmo) {
  98119. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  98120. }
  98121. this._gizmosEnabled.boundingBoxGizmo = value;
  98122. },
  98123. enumerable: true,
  98124. configurable: true
  98125. });
  98126. /**
  98127. * Disposes of the gizmo manager
  98128. */
  98129. GizmoManager.prototype.dispose = function () {
  98130. this.scene.onPointerObservable.remove(this._pointerObserver);
  98131. for (var key in this.gizmos) {
  98132. var gizmo = (this.gizmos[key]);
  98133. if (gizmo) {
  98134. gizmo.dispose();
  98135. }
  98136. }
  98137. this.boundingBoxDragBehavior.detach();
  98138. };
  98139. return GizmoManager;
  98140. }());
  98141. BABYLON.GizmoManager = GizmoManager;
  98142. })(BABYLON || (BABYLON = {}));
  98143. //# sourceMappingURL=babylon.gizmoManager.js.map
  98144. var BABYLON;
  98145. (function (BABYLON) {
  98146. /**
  98147. * Defines a target to use with MorphTargetManager
  98148. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98149. */
  98150. var MorphTarget = /** @class */ (function () {
  98151. /**
  98152. * Creates a new MorphTarget
  98153. * @param name defines the name of the target
  98154. * @param influence defines the influence to use
  98155. */
  98156. function MorphTarget(
  98157. /** defines the name of the target */
  98158. name, influence, scene) {
  98159. if (influence === void 0) { influence = 0; }
  98160. if (scene === void 0) { scene = null; }
  98161. this.name = name;
  98162. /**
  98163. * Gets or sets the list of animations
  98164. */
  98165. this.animations = new Array();
  98166. this._positions = null;
  98167. this._normals = null;
  98168. this._tangents = null;
  98169. /**
  98170. * Observable raised when the influence changes
  98171. */
  98172. this.onInfluenceChanged = new BABYLON.Observable();
  98173. this._animationPropertiesOverride = null;
  98174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98175. this.influence = influence;
  98176. }
  98177. Object.defineProperty(MorphTarget.prototype, "influence", {
  98178. /**
  98179. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  98180. */
  98181. get: function () {
  98182. return this._influence;
  98183. },
  98184. set: function (influence) {
  98185. if (this._influence === influence) {
  98186. return;
  98187. }
  98188. var previous = this._influence;
  98189. this._influence = influence;
  98190. if (this.onInfluenceChanged.hasObservers) {
  98191. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  98192. }
  98193. },
  98194. enumerable: true,
  98195. configurable: true
  98196. });
  98197. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  98198. /**
  98199. * Gets or sets the animation properties override
  98200. */
  98201. get: function () {
  98202. if (!this._animationPropertiesOverride && this._scene) {
  98203. return this._scene.animationPropertiesOverride;
  98204. }
  98205. return this._animationPropertiesOverride;
  98206. },
  98207. set: function (value) {
  98208. this._animationPropertiesOverride = value;
  98209. },
  98210. enumerable: true,
  98211. configurable: true
  98212. });
  98213. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  98214. /**
  98215. * Gets a boolean defining if the target contains position data
  98216. */
  98217. get: function () {
  98218. return !!this._positions;
  98219. },
  98220. enumerable: true,
  98221. configurable: true
  98222. });
  98223. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  98224. /**
  98225. * Gets a boolean defining if the target contains normal data
  98226. */
  98227. get: function () {
  98228. return !!this._normals;
  98229. },
  98230. enumerable: true,
  98231. configurable: true
  98232. });
  98233. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  98234. /**
  98235. * Gets a boolean defining if the target contains tangent data
  98236. */
  98237. get: function () {
  98238. return !!this._tangents;
  98239. },
  98240. enumerable: true,
  98241. configurable: true
  98242. });
  98243. /**
  98244. * Affects position data to this target
  98245. * @param data defines the position data to use
  98246. */
  98247. MorphTarget.prototype.setPositions = function (data) {
  98248. this._positions = data;
  98249. };
  98250. /**
  98251. * Gets the position data stored in this target
  98252. * @returns a FloatArray containing the position data (or null if not present)
  98253. */
  98254. MorphTarget.prototype.getPositions = function () {
  98255. return this._positions;
  98256. };
  98257. /**
  98258. * Affects normal data to this target
  98259. * @param data defines the normal data to use
  98260. */
  98261. MorphTarget.prototype.setNormals = function (data) {
  98262. this._normals = data;
  98263. };
  98264. /**
  98265. * Gets the normal data stored in this target
  98266. * @returns a FloatArray containing the normal data (or null if not present)
  98267. */
  98268. MorphTarget.prototype.getNormals = function () {
  98269. return this._normals;
  98270. };
  98271. /**
  98272. * Affects tangent data to this target
  98273. * @param data defines the tangent data to use
  98274. */
  98275. MorphTarget.prototype.setTangents = function (data) {
  98276. this._tangents = data;
  98277. };
  98278. /**
  98279. * Gets the tangent data stored in this target
  98280. * @returns a FloatArray containing the tangent data (or null if not present)
  98281. */
  98282. MorphTarget.prototype.getTangents = function () {
  98283. return this._tangents;
  98284. };
  98285. /**
  98286. * Serializes the current target into a Serialization object
  98287. * @returns the serialized object
  98288. */
  98289. MorphTarget.prototype.serialize = function () {
  98290. var serializationObject = {};
  98291. serializationObject.name = this.name;
  98292. serializationObject.influence = this.influence;
  98293. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  98294. if (this.hasNormals) {
  98295. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  98296. }
  98297. if (this.hasTangents) {
  98298. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  98299. }
  98300. // Animations
  98301. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  98302. return serializationObject;
  98303. };
  98304. // Statics
  98305. /**
  98306. * Creates a new target from serialized data
  98307. * @param serializationObject defines the serialized data to use
  98308. * @returns a new MorphTarget
  98309. */
  98310. MorphTarget.Parse = function (serializationObject) {
  98311. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  98312. result.setPositions(serializationObject.positions);
  98313. if (serializationObject.normals) {
  98314. result.setNormals(serializationObject.normals);
  98315. }
  98316. if (serializationObject.tangents) {
  98317. result.setTangents(serializationObject.tangents);
  98318. }
  98319. // Animations
  98320. if (serializationObject.animations) {
  98321. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  98322. var parsedAnimation = serializationObject.animations[animationIndex];
  98323. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  98324. }
  98325. }
  98326. return result;
  98327. };
  98328. /**
  98329. * Creates a MorphTarget from mesh data
  98330. * @param mesh defines the source mesh
  98331. * @param name defines the name to use for the new target
  98332. * @param influence defines the influence to attach to the target
  98333. * @returns a new MorphTarget
  98334. */
  98335. MorphTarget.FromMesh = function (mesh, name, influence) {
  98336. if (!name) {
  98337. name = mesh.name;
  98338. }
  98339. var result = new MorphTarget(name, influence, mesh.getScene());
  98340. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98342. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  98343. }
  98344. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  98345. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  98346. }
  98347. return result;
  98348. };
  98349. return MorphTarget;
  98350. }());
  98351. BABYLON.MorphTarget = MorphTarget;
  98352. })(BABYLON || (BABYLON = {}));
  98353. //# sourceMappingURL=babylon.morphTarget.js.map
  98354. var BABYLON;
  98355. (function (BABYLON) {
  98356. /**
  98357. * This class is used to deform meshes using morphing between different targets
  98358. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98359. */
  98360. var MorphTargetManager = /** @class */ (function () {
  98361. /**
  98362. * Creates a new MorphTargetManager
  98363. * @param scene defines the current scene
  98364. */
  98365. function MorphTargetManager(scene) {
  98366. if (scene === void 0) { scene = null; }
  98367. this._targets = new Array();
  98368. this._targetObservable = new Array();
  98369. this._activeTargets = new BABYLON.SmartArray(16);
  98370. this._supportsNormals = false;
  98371. this._supportsTangents = false;
  98372. this._vertexCount = 0;
  98373. this._uniqueId = 0;
  98374. this._tempInfluences = new Array();
  98375. if (!scene) {
  98376. scene = BABYLON.Engine.LastCreatedScene;
  98377. }
  98378. this._scene = scene;
  98379. if (this._scene) {
  98380. this._scene.morphTargetManagers.push(this);
  98381. this._uniqueId = this._scene.getUniqueId();
  98382. }
  98383. }
  98384. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  98385. /**
  98386. * Gets the unique ID of this manager
  98387. */
  98388. get: function () {
  98389. return this._uniqueId;
  98390. },
  98391. enumerable: true,
  98392. configurable: true
  98393. });
  98394. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  98395. /**
  98396. * Gets the number of vertices handled by this manager
  98397. */
  98398. get: function () {
  98399. return this._vertexCount;
  98400. },
  98401. enumerable: true,
  98402. configurable: true
  98403. });
  98404. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  98405. /**
  98406. * Gets a boolean indicating if this manager supports morphing of normals
  98407. */
  98408. get: function () {
  98409. return this._supportsNormals;
  98410. },
  98411. enumerable: true,
  98412. configurable: true
  98413. });
  98414. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  98415. /**
  98416. * Gets a boolean indicating if this manager supports morphing of tangents
  98417. */
  98418. get: function () {
  98419. return this._supportsTangents;
  98420. },
  98421. enumerable: true,
  98422. configurable: true
  98423. });
  98424. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  98425. /**
  98426. * Gets the number of targets stored in this manager
  98427. */
  98428. get: function () {
  98429. return this._targets.length;
  98430. },
  98431. enumerable: true,
  98432. configurable: true
  98433. });
  98434. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  98435. /**
  98436. * Gets the number of influencers (ie. the number of targets with influences > 0)
  98437. */
  98438. get: function () {
  98439. return this._activeTargets.length;
  98440. },
  98441. enumerable: true,
  98442. configurable: true
  98443. });
  98444. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  98445. /**
  98446. * Gets the list of influences (one per target)
  98447. */
  98448. get: function () {
  98449. return this._influences;
  98450. },
  98451. enumerable: true,
  98452. configurable: true
  98453. });
  98454. /**
  98455. * Gets the active target at specified index. An active target is a target with an influence > 0
  98456. * @param index defines the index to check
  98457. * @returns the requested target
  98458. */
  98459. MorphTargetManager.prototype.getActiveTarget = function (index) {
  98460. return this._activeTargets.data[index];
  98461. };
  98462. /**
  98463. * Gets the target at specified index
  98464. * @param index defines the index to check
  98465. * @returns the requested target
  98466. */
  98467. MorphTargetManager.prototype.getTarget = function (index) {
  98468. return this._targets[index];
  98469. };
  98470. /**
  98471. * Add a new target to this manager
  98472. * @param target defines the target to add
  98473. */
  98474. MorphTargetManager.prototype.addTarget = function (target) {
  98475. var _this = this;
  98476. this._targets.push(target);
  98477. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  98478. _this._syncActiveTargets(needUpdate);
  98479. }));
  98480. this._syncActiveTargets(true);
  98481. };
  98482. /**
  98483. * Removes a target from the manager
  98484. * @param target defines the target to remove
  98485. */
  98486. MorphTargetManager.prototype.removeTarget = function (target) {
  98487. var index = this._targets.indexOf(target);
  98488. if (index >= 0) {
  98489. this._targets.splice(index, 1);
  98490. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  98491. this._syncActiveTargets(true);
  98492. }
  98493. };
  98494. /**
  98495. * Serializes the current manager into a Serialization object
  98496. * @returns the serialized object
  98497. */
  98498. MorphTargetManager.prototype.serialize = function () {
  98499. var serializationObject = {};
  98500. serializationObject.id = this.uniqueId;
  98501. serializationObject.targets = [];
  98502. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98503. var target = _a[_i];
  98504. serializationObject.targets.push(target.serialize());
  98505. }
  98506. return serializationObject;
  98507. };
  98508. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  98509. var influenceCount = 0;
  98510. this._activeTargets.reset();
  98511. this._supportsNormals = true;
  98512. this._supportsTangents = true;
  98513. this._vertexCount = 0;
  98514. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98515. var target = _a[_i];
  98516. this._activeTargets.push(target);
  98517. this._tempInfluences[influenceCount++] = target.influence;
  98518. var positions = target.getPositions();
  98519. if (positions) {
  98520. this._supportsNormals = this._supportsNormals && target.hasNormals;
  98521. this._supportsTangents = this._supportsTangents && target.hasTangents;
  98522. var vertexCount = positions.length / 3;
  98523. if (this._vertexCount === 0) {
  98524. this._vertexCount = vertexCount;
  98525. }
  98526. else if (this._vertexCount !== vertexCount) {
  98527. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  98528. return;
  98529. }
  98530. }
  98531. }
  98532. if (!this._influences || this._influences.length !== influenceCount) {
  98533. this._influences = new Float32Array(influenceCount);
  98534. }
  98535. for (var index = 0; index < influenceCount; index++) {
  98536. this._influences[index] = this._tempInfluences[index];
  98537. }
  98538. if (needUpdate) {
  98539. this.synchronize();
  98540. }
  98541. };
  98542. /**
  98543. * Syncrhonize the targets with all the meshes using this morph target manager
  98544. */
  98545. MorphTargetManager.prototype.synchronize = function () {
  98546. if (!this._scene) {
  98547. return;
  98548. }
  98549. // Flag meshes as dirty to resync with the active targets
  98550. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  98551. var mesh = _a[_i];
  98552. if (mesh.morphTargetManager === this) {
  98553. mesh._syncGeometryWithMorphTargetManager();
  98554. }
  98555. }
  98556. };
  98557. // Statics
  98558. /**
  98559. * Creates a new MorphTargetManager from serialized data
  98560. * @param serializationObject defines the serialized data
  98561. * @param scene defines the hosting scene
  98562. * @returns the new MorphTargetManager
  98563. */
  98564. MorphTargetManager.Parse = function (serializationObject, scene) {
  98565. var result = new MorphTargetManager(scene);
  98566. result._uniqueId = serializationObject.id;
  98567. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  98568. var targetData = _a[_i];
  98569. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  98570. }
  98571. return result;
  98572. };
  98573. return MorphTargetManager;
  98574. }());
  98575. BABYLON.MorphTargetManager = MorphTargetManager;
  98576. })(BABYLON || (BABYLON = {}));
  98577. //# sourceMappingURL=babylon.morphTargetManager.js.map
  98578. var BABYLON;
  98579. (function (BABYLON) {
  98580. var Octree = /** @class */ (function () {
  98581. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  98582. if (maxDepth === void 0) { maxDepth = 2; }
  98583. this.maxDepth = maxDepth;
  98584. this.dynamicContent = new Array();
  98585. this._maxBlockCapacity = maxBlockCapacity || 64;
  98586. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  98587. this._creationFunc = creationFunc;
  98588. }
  98589. // Methods
  98590. Octree.prototype.update = function (worldMin, worldMax, entries) {
  98591. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  98592. };
  98593. Octree.prototype.addMesh = function (entry) {
  98594. for (var index = 0; index < this.blocks.length; index++) {
  98595. var block = this.blocks[index];
  98596. block.addEntry(entry);
  98597. }
  98598. };
  98599. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  98600. this._selectionContent.reset();
  98601. for (var index = 0; index < this.blocks.length; index++) {
  98602. var block = this.blocks[index];
  98603. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  98604. }
  98605. if (allowDuplicate) {
  98606. this._selectionContent.concat(this.dynamicContent);
  98607. }
  98608. else {
  98609. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98610. }
  98611. return this._selectionContent;
  98612. };
  98613. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  98614. this._selectionContent.reset();
  98615. for (var index = 0; index < this.blocks.length; index++) {
  98616. var block = this.blocks[index];
  98617. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  98618. }
  98619. if (allowDuplicate) {
  98620. this._selectionContent.concat(this.dynamicContent);
  98621. }
  98622. else {
  98623. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98624. }
  98625. return this._selectionContent;
  98626. };
  98627. Octree.prototype.intersectsRay = function (ray) {
  98628. this._selectionContent.reset();
  98629. for (var index = 0; index < this.blocks.length; index++) {
  98630. var block = this.blocks[index];
  98631. block.intersectsRay(ray, this._selectionContent);
  98632. }
  98633. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98634. return this._selectionContent;
  98635. };
  98636. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  98637. target.blocks = new Array();
  98638. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  98639. // Segmenting space
  98640. for (var x = 0; x < 2; x++) {
  98641. for (var y = 0; y < 2; y++) {
  98642. for (var z = 0; z < 2; z++) {
  98643. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  98644. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  98645. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  98646. block.addEntries(entries);
  98647. target.blocks.push(block);
  98648. }
  98649. }
  98650. }
  98651. };
  98652. Octree.CreationFuncForMeshes = function (entry, block) {
  98653. var boundingInfo = entry.getBoundingInfo();
  98654. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98655. block.entries.push(entry);
  98656. }
  98657. };
  98658. Octree.CreationFuncForSubMeshes = function (entry, block) {
  98659. var boundingInfo = entry.getBoundingInfo();
  98660. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98661. block.entries.push(entry);
  98662. }
  98663. };
  98664. return Octree;
  98665. }());
  98666. BABYLON.Octree = Octree;
  98667. })(BABYLON || (BABYLON = {}));
  98668. //# sourceMappingURL=babylon.octree.js.map
  98669. var BABYLON;
  98670. (function (BABYLON) {
  98671. /**
  98672. * Class used to store a cell in an octree
  98673. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98674. */
  98675. var OctreeBlock = /** @class */ (function () {
  98676. /**
  98677. * Creates a new block
  98678. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  98679. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  98680. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98681. * @param depth defines the current depth of this block in the octree
  98682. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  98683. * @param creationFunc defines a callback to call when an element is added to the block
  98684. */
  98685. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  98686. /**
  98687. * Gets the content of the current block
  98688. */
  98689. this.entries = new Array();
  98690. this._boundingVectors = new Array();
  98691. this._capacity = capacity;
  98692. this._depth = depth;
  98693. this._maxDepth = maxDepth;
  98694. this._creationFunc = creationFunc;
  98695. this._minPoint = minPoint;
  98696. this._maxPoint = maxPoint;
  98697. this._boundingVectors.push(minPoint.clone());
  98698. this._boundingVectors.push(maxPoint.clone());
  98699. this._boundingVectors.push(minPoint.clone());
  98700. this._boundingVectors[2].x = maxPoint.x;
  98701. this._boundingVectors.push(minPoint.clone());
  98702. this._boundingVectors[3].y = maxPoint.y;
  98703. this._boundingVectors.push(minPoint.clone());
  98704. this._boundingVectors[4].z = maxPoint.z;
  98705. this._boundingVectors.push(maxPoint.clone());
  98706. this._boundingVectors[5].z = minPoint.z;
  98707. this._boundingVectors.push(maxPoint.clone());
  98708. this._boundingVectors[6].x = minPoint.x;
  98709. this._boundingVectors.push(maxPoint.clone());
  98710. this._boundingVectors[7].y = minPoint.y;
  98711. }
  98712. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  98713. // Property
  98714. /**
  98715. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98716. */
  98717. get: function () {
  98718. return this._capacity;
  98719. },
  98720. enumerable: true,
  98721. configurable: true
  98722. });
  98723. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  98724. /**
  98725. * Gets the minimum vector (in world space) of the block's bounding box
  98726. */
  98727. get: function () {
  98728. return this._minPoint;
  98729. },
  98730. enumerable: true,
  98731. configurable: true
  98732. });
  98733. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  98734. /**
  98735. * Gets the maximum vector (in world space) of the block's bounding box
  98736. */
  98737. get: function () {
  98738. return this._maxPoint;
  98739. },
  98740. enumerable: true,
  98741. configurable: true
  98742. });
  98743. // Methods
  98744. /**
  98745. * Add a new element to this block
  98746. * @param entry defines the element to add
  98747. */
  98748. OctreeBlock.prototype.addEntry = function (entry) {
  98749. if (this.blocks) {
  98750. for (var index = 0; index < this.blocks.length; index++) {
  98751. var block = this.blocks[index];
  98752. block.addEntry(entry);
  98753. }
  98754. return;
  98755. }
  98756. this._creationFunc(entry, this);
  98757. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  98758. this.createInnerBlocks();
  98759. }
  98760. };
  98761. /**
  98762. * Add an array of elements to this block
  98763. * @param entries defines the array of elements to add
  98764. */
  98765. OctreeBlock.prototype.addEntries = function (entries) {
  98766. for (var index = 0; index < entries.length; index++) {
  98767. var mesh = entries[index];
  98768. this.addEntry(mesh);
  98769. }
  98770. };
  98771. /**
  98772. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  98773. * @param frustumPlanes defines the frustum planes to test
  98774. * @param selection defines the array to store current content if selection is positive
  98775. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98776. */
  98777. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  98778. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  98779. if (this.blocks) {
  98780. for (var index = 0; index < this.blocks.length; index++) {
  98781. var block = this.blocks[index];
  98782. block.select(frustumPlanes, selection, allowDuplicate);
  98783. }
  98784. return;
  98785. }
  98786. if (allowDuplicate) {
  98787. selection.concat(this.entries);
  98788. }
  98789. else {
  98790. selection.concatWithNoDuplicate(this.entries);
  98791. }
  98792. }
  98793. };
  98794. /**
  98795. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  98796. * @param sphereCenter defines the bounding sphere center
  98797. * @param sphereRadius defines the bounding sphere radius
  98798. * @param selection defines the array to store current content if selection is positive
  98799. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98800. */
  98801. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  98802. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  98803. if (this.blocks) {
  98804. for (var index = 0; index < this.blocks.length; index++) {
  98805. var block = this.blocks[index];
  98806. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  98807. }
  98808. return;
  98809. }
  98810. if (allowDuplicate) {
  98811. selection.concat(this.entries);
  98812. }
  98813. else {
  98814. selection.concatWithNoDuplicate(this.entries);
  98815. }
  98816. }
  98817. };
  98818. /**
  98819. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  98820. * @param ray defines the ray to test with
  98821. * @param selection defines the array to store current content if selection is positive
  98822. */
  98823. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  98824. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  98825. if (this.blocks) {
  98826. for (var index = 0; index < this.blocks.length; index++) {
  98827. var block = this.blocks[index];
  98828. block.intersectsRay(ray, selection);
  98829. }
  98830. return;
  98831. }
  98832. selection.concatWithNoDuplicate(this.entries);
  98833. }
  98834. };
  98835. /**
  98836. * Subdivide the content into child blocks (this block will then be empty)
  98837. */
  98838. OctreeBlock.prototype.createInnerBlocks = function () {
  98839. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  98840. };
  98841. return OctreeBlock;
  98842. }());
  98843. BABYLON.OctreeBlock = OctreeBlock;
  98844. })(BABYLON || (BABYLON = {}));
  98845. //# sourceMappingURL=babylon.octreeBlock.js.map
  98846. var BABYLON;
  98847. (function (BABYLON) {
  98848. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  98849. if (maxCapacity === void 0) { maxCapacity = 64; }
  98850. if (maxDepth === void 0) { maxDepth = 2; }
  98851. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98852. if (!component) {
  98853. component = new OctreeSceneComponent(this);
  98854. this._addComponent(component);
  98855. }
  98856. if (!this._selectionOctree) {
  98857. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  98858. }
  98859. var worldExtends = this.getWorldExtends();
  98860. // Update octree
  98861. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  98862. return this._selectionOctree;
  98863. };
  98864. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  98865. get: function () {
  98866. return this._selectionOctree;
  98867. },
  98868. enumerable: true,
  98869. configurable: true
  98870. });
  98871. /**
  98872. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  98873. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  98874. * @param maxCapacity defines the maximum size of each block (64 by default)
  98875. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  98876. * @returns the new octree
  98877. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  98878. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98879. */
  98880. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  98881. if (maxCapacity === void 0) { maxCapacity = 64; }
  98882. if (maxDepth === void 0) { maxDepth = 2; }
  98883. var scene = this.getScene();
  98884. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98885. if (!component) {
  98886. component = new OctreeSceneComponent(scene);
  98887. scene._addComponent(component);
  98888. }
  98889. if (!this._submeshesOctree) {
  98890. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  98891. }
  98892. this.computeWorldMatrix(true);
  98893. var boundingInfo = this.getBoundingInfo();
  98894. // Update octree
  98895. var bbox = boundingInfo.boundingBox;
  98896. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  98897. return this._submeshesOctree;
  98898. };
  98899. /**
  98900. * Defines the octree scene component responsible to manage any octrees
  98901. * in a given scene.
  98902. */
  98903. var OctreeSceneComponent = /** @class */ (function () {
  98904. /**
  98905. * Creates a new instance of the component for the given scene
  98906. * @param scene Defines the scene to register the component in
  98907. */
  98908. function OctreeSceneComponent(scene) {
  98909. /**
  98910. * The component name helpfull to identify the component in the list of scene components.
  98911. */
  98912. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  98913. /**
  98914. * Indicates if the meshes have been checked to make sure they are isEnabled()
  98915. */
  98916. this.checksIsEnabled = true;
  98917. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  98918. this.scene = scene;
  98919. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  98920. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  98921. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  98922. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  98923. }
  98924. /**
  98925. * Registers the component in a given scene
  98926. */
  98927. OctreeSceneComponent.prototype.register = function () {
  98928. var _this = this;
  98929. this.scene.onMeshRemovedObservable.add(function (mesh) {
  98930. var sceneOctree = _this.scene.selectionOctree;
  98931. if (sceneOctree !== undefined && sceneOctree !== null) {
  98932. var index = sceneOctree.dynamicContent.indexOf(mesh);
  98933. if (index !== -1) {
  98934. sceneOctree.dynamicContent.splice(index, 1);
  98935. }
  98936. }
  98937. });
  98938. this.scene.onMeshImportedObservable.add(function (mesh) {
  98939. var sceneOctree = _this.scene.selectionOctree;
  98940. if (sceneOctree !== undefined && sceneOctree !== null) {
  98941. sceneOctree.addMesh(mesh);
  98942. }
  98943. });
  98944. };
  98945. /**
  98946. * Return the list of active meshes
  98947. * @returns the list of active meshes
  98948. */
  98949. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  98950. if (this.scene._selectionOctree) {
  98951. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  98952. return selection;
  98953. }
  98954. return this.scene._getDefaultMeshCandidates();
  98955. };
  98956. /**
  98957. * Return the list of active sub meshes
  98958. * @param mesh The mesh to get the candidates sub meshes from
  98959. * @returns the list of active sub meshes
  98960. */
  98961. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  98962. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  98963. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  98964. return intersections;
  98965. }
  98966. return this.scene._getDefaultSubMeshCandidates(mesh);
  98967. };
  98968. /**
  98969. * Return the list of sub meshes intersecting with a given local ray
  98970. * @param mesh defines the mesh to find the submesh for
  98971. * @param localRay defines the ray in local space
  98972. * @returns the list of intersecting sub meshes
  98973. */
  98974. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  98975. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  98976. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  98977. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  98978. return intersections;
  98979. }
  98980. return this.scene._getDefaultSubMeshCandidates(mesh);
  98981. };
  98982. /**
  98983. * Return the list of sub meshes colliding with a collider
  98984. * @param mesh defines the mesh to find the submesh for
  98985. * @param collider defines the collider to evaluate the collision against
  98986. * @returns the list of colliding sub meshes
  98987. */
  98988. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  98989. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  98990. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  98991. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  98992. return intersections;
  98993. }
  98994. return this.scene._getDefaultSubMeshCandidates(mesh);
  98995. };
  98996. /**
  98997. * Rebuilds the elements related to this component in case of
  98998. * context lost for instance.
  98999. */
  99000. OctreeSceneComponent.prototype.rebuild = function () {
  99001. // Nothing to do here.
  99002. };
  99003. /**
  99004. * Disposes the component and the associated ressources.
  99005. */
  99006. OctreeSceneComponent.prototype.dispose = function () {
  99007. // Nothing to do here.
  99008. };
  99009. return OctreeSceneComponent;
  99010. }());
  99011. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  99012. })(BABYLON || (BABYLON = {}));
  99013. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  99014. var BABYLON;
  99015. (function (BABYLON) {
  99016. /**
  99017. * Postprocess used to generate anaglyphic rendering
  99018. */
  99019. var AnaglyphPostProcess = /** @class */ (function (_super) {
  99020. __extends(AnaglyphPostProcess, _super);
  99021. /**
  99022. * Creates a new AnaglyphPostProcess
  99023. * @param name defines postprocess name
  99024. * @param options defines creation options or target ratio scale
  99025. * @param rigCameras defines cameras using this postprocess
  99026. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  99027. * @param engine defines hosting engine
  99028. * @param reusable defines if the postprocess will be reused multiple times per frame
  99029. */
  99030. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  99031. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  99032. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99033. _this.onApplyObservable.add(function (effect) {
  99034. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  99035. });
  99036. return _this;
  99037. }
  99038. return AnaglyphPostProcess;
  99039. }(BABYLON.PostProcess));
  99040. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  99041. })(BABYLON || (BABYLON = {}));
  99042. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  99043. var BABYLON;
  99044. (function (BABYLON) {
  99045. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  99046. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99047. });
  99048. /**
  99049. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  99050. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99051. */
  99052. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  99053. __extends(AnaglyphArcRotateCamera, _super);
  99054. /**
  99055. * Creates a new AnaglyphArcRotateCamera
  99056. * @param name defines camera name
  99057. * @param alpha defines alpha angle (in radians)
  99058. * @param beta defines beta angle (in radians)
  99059. * @param radius defines radius
  99060. * @param target defines camera target
  99061. * @param interaxialDistance defines distance between each color axis
  99062. * @param scene defines the hosting scene
  99063. */
  99064. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  99065. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99066. _this.interaxialDistance = interaxialDistance;
  99067. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99068. return _this;
  99069. }
  99070. /**
  99071. * Gets camera class name
  99072. * @returns AnaglyphArcRotateCamera
  99073. */
  99074. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  99075. return "AnaglyphArcRotateCamera";
  99076. };
  99077. return AnaglyphArcRotateCamera;
  99078. }(BABYLON.ArcRotateCamera));
  99079. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  99080. })(BABYLON || (BABYLON = {}));
  99081. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  99082. var BABYLON;
  99083. (function (BABYLON) {
  99084. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  99085. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99086. });
  99087. /**
  99088. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  99089. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99090. */
  99091. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  99092. __extends(AnaglyphFreeCamera, _super);
  99093. /**
  99094. * Creates a new AnaglyphFreeCamera
  99095. * @param name defines camera name
  99096. * @param position defines initial position
  99097. * @param interaxialDistance defines distance between each color axis
  99098. * @param scene defines the hosting scene
  99099. */
  99100. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  99101. var _this = _super.call(this, name, position, scene) || this;
  99102. _this.interaxialDistance = interaxialDistance;
  99103. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99104. return _this;
  99105. }
  99106. /**
  99107. * Gets camera class name
  99108. * @returns AnaglyphFreeCamera
  99109. */
  99110. AnaglyphFreeCamera.prototype.getClassName = function () {
  99111. return "AnaglyphFreeCamera";
  99112. };
  99113. return AnaglyphFreeCamera;
  99114. }(BABYLON.FreeCamera));
  99115. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  99116. })(BABYLON || (BABYLON = {}));
  99117. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  99118. var BABYLON;
  99119. (function (BABYLON) {
  99120. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  99121. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99122. });
  99123. /**
  99124. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  99125. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99126. */
  99127. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  99128. __extends(AnaglyphGamepadCamera, _super);
  99129. /**
  99130. * Creates a new AnaglyphGamepadCamera
  99131. * @param name defines camera name
  99132. * @param position defines initial position
  99133. * @param interaxialDistance defines distance between each color axis
  99134. * @param scene defines the hosting scene
  99135. */
  99136. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  99137. var _this = _super.call(this, name, position, scene) || this;
  99138. _this.interaxialDistance = interaxialDistance;
  99139. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99140. return _this;
  99141. }
  99142. /**
  99143. * Gets camera class name
  99144. * @returns AnaglyphGamepadCamera
  99145. */
  99146. AnaglyphGamepadCamera.prototype.getClassName = function () {
  99147. return "AnaglyphGamepadCamera";
  99148. };
  99149. return AnaglyphGamepadCamera;
  99150. }(BABYLON.GamepadCamera));
  99151. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  99152. })(BABYLON || (BABYLON = {}));
  99153. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  99154. var BABYLON;
  99155. (function (BABYLON) {
  99156. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  99157. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99158. });
  99159. /**
  99160. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  99161. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99162. */
  99163. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  99164. __extends(AnaglyphUniversalCamera, _super);
  99165. /**
  99166. * Creates a new AnaglyphUniversalCamera
  99167. * @param name defines camera name
  99168. * @param position defines initial position
  99169. * @param interaxialDistance defines distance between each color axis
  99170. * @param scene defines the hosting scene
  99171. */
  99172. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  99173. var _this = _super.call(this, name, position, scene) || this;
  99174. _this.interaxialDistance = interaxialDistance;
  99175. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99176. return _this;
  99177. }
  99178. /**
  99179. * Gets camera class name
  99180. * @returns AnaglyphUniversalCamera
  99181. */
  99182. AnaglyphUniversalCamera.prototype.getClassName = function () {
  99183. return "AnaglyphUniversalCamera";
  99184. };
  99185. return AnaglyphUniversalCamera;
  99186. }(BABYLON.UniversalCamera));
  99187. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  99188. })(BABYLON || (BABYLON = {}));
  99189. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  99190. var BABYLON;
  99191. (function (BABYLON) {
  99192. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  99193. __extends(StereoscopicInterlacePostProcess, _super);
  99194. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  99195. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  99196. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99197. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99198. _this.onSizeChangedObservable.add(function () {
  99199. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99200. });
  99201. _this.onApplyObservable.add(function (effect) {
  99202. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  99203. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  99204. });
  99205. return _this;
  99206. }
  99207. return StereoscopicInterlacePostProcess;
  99208. }(BABYLON.PostProcess));
  99209. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  99210. })(BABYLON || (BABYLON = {}));
  99211. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  99212. var BABYLON;
  99213. (function (BABYLON) {
  99214. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  99215. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99216. });
  99217. /**
  99218. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  99219. * @see http://doc.babylonjs.com/features/cameras
  99220. */
  99221. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  99222. __extends(StereoscopicArcRotateCamera, _super);
  99223. /**
  99224. * Creates a new StereoscopicArcRotateCamera
  99225. * @param name defines camera name
  99226. * @param alpha defines alpha angle (in radians)
  99227. * @param beta defines beta angle (in radians)
  99228. * @param radius defines radius
  99229. * @param target defines camera target
  99230. * @param interaxialDistance defines distance between each color axis
  99231. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99232. * @param scene defines the hosting scene
  99233. */
  99234. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  99235. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99236. _this.interaxialDistance = interaxialDistance;
  99237. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99238. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99239. return _this;
  99240. }
  99241. /**
  99242. * Gets camera class name
  99243. * @returns StereoscopicArcRotateCamera
  99244. */
  99245. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  99246. return "StereoscopicArcRotateCamera";
  99247. };
  99248. return StereoscopicArcRotateCamera;
  99249. }(BABYLON.ArcRotateCamera));
  99250. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  99251. })(BABYLON || (BABYLON = {}));
  99252. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  99253. var BABYLON;
  99254. (function (BABYLON) {
  99255. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99256. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99257. });
  99258. /**
  99259. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  99260. * @see http://doc.babylonjs.com/features/cameras
  99261. */
  99262. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  99263. __extends(StereoscopicFreeCamera, _super);
  99264. /**
  99265. * Creates a new StereoscopicFreeCamera
  99266. * @param name defines camera name
  99267. * @param position defines initial position
  99268. * @param interaxialDistance defines distance between each color axis
  99269. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99270. * @param scene defines the hosting scene
  99271. */
  99272. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99273. var _this = _super.call(this, name, position, scene) || this;
  99274. _this.interaxialDistance = interaxialDistance;
  99275. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99276. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99277. return _this;
  99278. }
  99279. /**
  99280. * Gets camera class name
  99281. * @returns StereoscopicFreeCamera
  99282. */
  99283. StereoscopicFreeCamera.prototype.getClassName = function () {
  99284. return "StereoscopicFreeCamera";
  99285. };
  99286. return StereoscopicFreeCamera;
  99287. }(BABYLON.FreeCamera));
  99288. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  99289. })(BABYLON || (BABYLON = {}));
  99290. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  99291. var BABYLON;
  99292. (function (BABYLON) {
  99293. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  99294. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99295. });
  99296. /**
  99297. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  99298. * @see http://doc.babylonjs.com/features/cameras
  99299. */
  99300. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  99301. __extends(StereoscopicGamepadCamera, _super);
  99302. /**
  99303. * Creates a new StereoscopicGamepadCamera
  99304. * @param name defines camera name
  99305. * @param position defines initial position
  99306. * @param interaxialDistance defines distance between each color axis
  99307. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99308. * @param scene defines the hosting scene
  99309. */
  99310. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99311. var _this = _super.call(this, name, position, scene) || this;
  99312. _this.interaxialDistance = interaxialDistance;
  99313. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99314. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99315. return _this;
  99316. }
  99317. /**
  99318. * Gets camera class name
  99319. * @returns StereoscopicGamepadCamera
  99320. */
  99321. StereoscopicGamepadCamera.prototype.getClassName = function () {
  99322. return "StereoscopicGamepadCamera";
  99323. };
  99324. return StereoscopicGamepadCamera;
  99325. }(BABYLON.GamepadCamera));
  99326. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  99327. })(BABYLON || (BABYLON = {}));
  99328. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  99329. var BABYLON;
  99330. (function (BABYLON) {
  99331. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99332. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99333. });
  99334. /**
  99335. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  99336. * @see http://doc.babylonjs.com/features/cameras
  99337. */
  99338. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  99339. __extends(StereoscopicUniversalCamera, _super);
  99340. /**
  99341. * Creates a new StereoscopicUniversalCamera
  99342. * @param name defines camera name
  99343. * @param position defines initial position
  99344. * @param interaxialDistance defines distance between each color axis
  99345. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99346. * @param scene defines the hosting scene
  99347. */
  99348. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99349. var _this = _super.call(this, name, position, scene) || this;
  99350. _this.interaxialDistance = interaxialDistance;
  99351. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99352. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99353. return _this;
  99354. }
  99355. /**
  99356. * Gets camera class name
  99357. * @returns StereoscopicUniversalCamera
  99358. */
  99359. StereoscopicUniversalCamera.prototype.getClassName = function () {
  99360. return "StereoscopicUniversalCamera";
  99361. };
  99362. return StereoscopicUniversalCamera;
  99363. }(BABYLON.UniversalCamera));
  99364. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  99365. })(BABYLON || (BABYLON = {}));
  99366. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  99367. var BABYLON;
  99368. (function (BABYLON) {
  99369. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  99370. __extends(VRDistortionCorrectionPostProcess, _super);
  99371. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  99372. var _this = _super.call(this, name, "vrDistortionCorrection", [
  99373. 'LensCenter',
  99374. 'Scale',
  99375. 'ScaleIn',
  99376. 'HmdWarpParam'
  99377. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  99378. _this._isRightEye = isRightEye;
  99379. _this._distortionFactors = vrMetrics.distortionK;
  99380. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  99381. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  99382. _this.adaptScaleToCurrentViewport = true;
  99383. _this.onSizeChangedObservable.add(function () {
  99384. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  99385. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  99386. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  99387. });
  99388. _this.onApplyObservable.add(function (effect) {
  99389. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  99390. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  99391. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  99392. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  99393. });
  99394. return _this;
  99395. }
  99396. return VRDistortionCorrectionPostProcess;
  99397. }(BABYLON.PostProcess));
  99398. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  99399. })(BABYLON || (BABYLON = {}));
  99400. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  99401. var BABYLON;
  99402. (function (BABYLON) {
  99403. /**
  99404. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  99405. * Screen rotation is taken into account.
  99406. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99407. */
  99408. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  99409. /**
  99410. * Instantiates a new input
  99411. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99412. */
  99413. function FreeCameraDeviceOrientationInput() {
  99414. var _this = this;
  99415. this._screenOrientationAngle = 0;
  99416. this._screenQuaternion = new BABYLON.Quaternion();
  99417. this._alpha = 0;
  99418. this._beta = 0;
  99419. this._gamma = 0;
  99420. this._orientationChanged = function () {
  99421. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  99422. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  99423. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  99424. };
  99425. this._deviceOrientation = function (evt) {
  99426. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  99427. _this._beta = evt.beta !== null ? evt.beta : 0;
  99428. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  99429. };
  99430. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  99431. this._orientationChanged();
  99432. }
  99433. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  99434. /**
  99435. * Define the camera controlled by the input.
  99436. */
  99437. get: function () {
  99438. return this._camera;
  99439. },
  99440. set: function (camera) {
  99441. this._camera = camera;
  99442. if (this._camera != null && !this._camera.rotationQuaternion) {
  99443. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  99444. }
  99445. },
  99446. enumerable: true,
  99447. configurable: true
  99448. });
  99449. /**
  99450. * Attach the input controls to a specific dom element to get the input from.
  99451. * @param element Defines the element the controls should be listened from
  99452. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99453. */
  99454. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99455. window.addEventListener("orientationchange", this._orientationChanged);
  99456. window.addEventListener("deviceorientation", this._deviceOrientation);
  99457. //In certain cases, the attach control is called AFTER orientation was changed,
  99458. //So this is needed.
  99459. this._orientationChanged();
  99460. };
  99461. /**
  99462. * Detach the current controls from the specified dom element.
  99463. * @param element Defines the element to stop listening the inputs from
  99464. */
  99465. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  99466. window.removeEventListener("orientationchange", this._orientationChanged);
  99467. window.removeEventListener("deviceorientation", this._deviceOrientation);
  99468. };
  99469. /**
  99470. * Update the current camera state depending on the inputs that have been used this frame.
  99471. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99472. */
  99473. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  99474. //if no device orientation provided, don't update the rotation.
  99475. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  99476. if (!this._alpha)
  99477. return;
  99478. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  99479. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  99480. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  99481. //Mirror on XY Plane
  99482. this._camera.rotationQuaternion.z *= -1;
  99483. this._camera.rotationQuaternion.w *= -1;
  99484. };
  99485. /**
  99486. * Gets the class name of the current intput.
  99487. * @returns the class name
  99488. */
  99489. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  99490. return "FreeCameraDeviceOrientationInput";
  99491. };
  99492. /**
  99493. * Get the friendly name associated with the input class.
  99494. * @returns the input friendly name
  99495. */
  99496. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  99497. return "deviceOrientation";
  99498. };
  99499. return FreeCameraDeviceOrientationInput;
  99500. }());
  99501. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  99502. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  99503. })(BABYLON || (BABYLON = {}));
  99504. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  99505. var BABYLON;
  99506. (function (BABYLON) {
  99507. /**
  99508. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  99509. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99510. */
  99511. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  99512. /**
  99513. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  99514. */
  99515. function ArcRotateCameraVRDeviceOrientationInput() {
  99516. /**
  99517. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  99518. */
  99519. this.alphaCorrection = 1;
  99520. /**
  99521. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  99522. */
  99523. this.betaCorrection = 1;
  99524. /**
  99525. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  99526. */
  99527. this.gammaCorrection = 1;
  99528. this._alpha = 0;
  99529. this._gamma = 0;
  99530. this._dirty = false;
  99531. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  99532. }
  99533. /**
  99534. * Attach the input controls to a specific dom element to get the input from.
  99535. * @param element Defines the element the controls should be listened from
  99536. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99537. */
  99538. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99539. this.camera.attachControl(element, noPreventDefault);
  99540. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  99541. };
  99542. /** @hidden */
  99543. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  99544. if (evt.alpha !== null) {
  99545. this._alpha = +evt.alpha | 0;
  99546. }
  99547. if (evt.gamma !== null) {
  99548. this._gamma = +evt.gamma | 0;
  99549. }
  99550. this._dirty = true;
  99551. };
  99552. /**
  99553. * Update the current camera state depending on the inputs that have been used this frame.
  99554. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99555. */
  99556. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  99557. if (this._dirty) {
  99558. this._dirty = false;
  99559. if (this._gamma < 0) {
  99560. this._gamma = 180 + this._gamma;
  99561. }
  99562. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  99563. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  99564. }
  99565. };
  99566. /**
  99567. * Detach the current controls from the specified dom element.
  99568. * @param element Defines the element to stop listening the inputs from
  99569. */
  99570. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  99571. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  99572. };
  99573. /**
  99574. * Gets the class name of the current intput.
  99575. * @returns the class name
  99576. */
  99577. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  99578. return "ArcRotateCameraVRDeviceOrientationInput";
  99579. };
  99580. /**
  99581. * Get the friendly name associated with the input class.
  99582. * @returns the input friendly name
  99583. */
  99584. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  99585. return "VRDeviceOrientation";
  99586. };
  99587. return ArcRotateCameraVRDeviceOrientationInput;
  99588. }());
  99589. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  99590. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  99591. })(BABYLON || (BABYLON = {}));
  99592. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  99593. var BABYLON;
  99594. (function (BABYLON) {
  99595. /**
  99596. * This represents all the required metrics to create a VR camera.
  99597. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  99598. */
  99599. var VRCameraMetrics = /** @class */ (function () {
  99600. function VRCameraMetrics() {
  99601. /**
  99602. * Define if the current vr camera should compensate the distortion of the lense or not.
  99603. */
  99604. this.compensateDistortion = true;
  99605. }
  99606. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  99607. /**
  99608. * Gets the rendering aspect ratio based on the provided resolutions.
  99609. */
  99610. get: function () {
  99611. return this.hResolution / (2 * this.vResolution);
  99612. },
  99613. enumerable: true,
  99614. configurable: true
  99615. });
  99616. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  99617. /**
  99618. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  99619. */
  99620. get: function () {
  99621. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  99622. },
  99623. enumerable: true,
  99624. configurable: true
  99625. });
  99626. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  99627. /**
  99628. * @hidden
  99629. */
  99630. get: function () {
  99631. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99632. var h = (4 * meters) / this.hScreenSize;
  99633. return BABYLON.Matrix.Translation(h, 0, 0);
  99634. },
  99635. enumerable: true,
  99636. configurable: true
  99637. });
  99638. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  99639. /**
  99640. * @hidden
  99641. */
  99642. get: function () {
  99643. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99644. var h = (4 * meters) / this.hScreenSize;
  99645. return BABYLON.Matrix.Translation(-h, 0, 0);
  99646. },
  99647. enumerable: true,
  99648. configurable: true
  99649. });
  99650. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  99651. /**
  99652. * @hidden
  99653. */
  99654. get: function () {
  99655. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  99656. },
  99657. enumerable: true,
  99658. configurable: true
  99659. });
  99660. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  99661. /**
  99662. * @hidden
  99663. */
  99664. get: function () {
  99665. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  99666. },
  99667. enumerable: true,
  99668. configurable: true
  99669. });
  99670. /**
  99671. * Get the default VRMetrics based on the most generic setup.
  99672. * @returns the default vr metrics
  99673. */
  99674. VRCameraMetrics.GetDefault = function () {
  99675. var result = new VRCameraMetrics();
  99676. result.hResolution = 1280;
  99677. result.vResolution = 800;
  99678. result.hScreenSize = 0.149759993;
  99679. result.vScreenSize = 0.0935999975;
  99680. result.vScreenCenter = 0.0467999987;
  99681. result.eyeToScreenDistance = 0.0410000011;
  99682. result.lensSeparationDistance = 0.0635000020;
  99683. result.interpupillaryDistance = 0.0640000030;
  99684. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  99685. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  99686. result.postProcessScaleFactor = 1.714605507808412;
  99687. result.lensCenterOffset = 0.151976421;
  99688. return result;
  99689. };
  99690. return VRCameraMetrics;
  99691. }());
  99692. BABYLON.VRCameraMetrics = VRCameraMetrics;
  99693. })(BABYLON || (BABYLON = {}));
  99694. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  99695. var BABYLON;
  99696. (function (BABYLON) {
  99697. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  99698. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99699. });
  99700. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  99701. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99702. });
  99703. /**
  99704. * This represents a WebVR camera.
  99705. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  99706. * @example http://doc.babylonjs.com/how_to/webvr_camera
  99707. */
  99708. var WebVRFreeCamera = /** @class */ (function (_super) {
  99709. __extends(WebVRFreeCamera, _super);
  99710. /**
  99711. * Instantiates a WebVRFreeCamera.
  99712. * @param name The name of the WebVRFreeCamera
  99713. * @param position The starting anchor position for the camera
  99714. * @param scene The scene the camera belongs to
  99715. * @param webVROptions a set of customizable options for the webVRCamera
  99716. */
  99717. function WebVRFreeCamera(name, position, scene, webVROptions) {
  99718. if (webVROptions === void 0) { webVROptions = {}; }
  99719. var _this = _super.call(this, name, position, scene) || this;
  99720. _this.webVROptions = webVROptions;
  99721. /**
  99722. * @hidden
  99723. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  99724. */
  99725. _this._vrDevice = null;
  99726. /**
  99727. * The rawPose of the vrDevice.
  99728. */
  99729. _this.rawPose = null;
  99730. _this._specsVersion = "1.1";
  99731. _this._attached = false;
  99732. _this._descendants = [];
  99733. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  99734. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  99735. /** @hidden */
  99736. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  99737. _this._standingMatrix = null;
  99738. /**
  99739. * Represents device position in babylon space.
  99740. */
  99741. _this.devicePosition = BABYLON.Vector3.Zero();
  99742. /**
  99743. * Represents device rotation in babylon space.
  99744. */
  99745. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  99746. /**
  99747. * The scale of the device to be used when translating from device space to babylon space.
  99748. */
  99749. _this.deviceScaleFactor = 1;
  99750. _this._deviceToWorld = BABYLON.Matrix.Identity();
  99751. _this._worldToDevice = BABYLON.Matrix.Identity();
  99752. /**
  99753. * References to the webVR controllers for the vrDevice.
  99754. */
  99755. _this.controllers = [];
  99756. /**
  99757. * Emits an event when a controller is attached.
  99758. */
  99759. _this.onControllersAttachedObservable = new BABYLON.Observable();
  99760. /**
  99761. * Emits an event when a controller's mesh has been loaded;
  99762. */
  99763. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99764. /**
  99765. * Emits an event when the HMD's pose has been updated.
  99766. */
  99767. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  99768. _this._poseSet = false;
  99769. /**
  99770. * If the rig cameras be used as parent instead of this camera.
  99771. */
  99772. _this.rigParenting = true;
  99773. _this._defaultHeight = undefined;
  99774. _this._htmlElementAttached = null;
  99775. _this._detachIfAttached = function () {
  99776. var vrDisplay = _this.getEngine().getVRDevice();
  99777. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  99778. _this.detachControl(_this._htmlElementAttached);
  99779. }
  99780. };
  99781. _this._workingVector = BABYLON.Vector3.Zero();
  99782. _this._oneVector = BABYLON.Vector3.One();
  99783. _this._workingMatrix = BABYLON.Matrix.Identity();
  99784. _this._tmpMatrix = new BABYLON.Matrix();
  99785. _this._cache.position = BABYLON.Vector3.Zero();
  99786. if (webVROptions.defaultHeight) {
  99787. _this._defaultHeight = webVROptions.defaultHeight;
  99788. _this.position.y = _this._defaultHeight;
  99789. }
  99790. _this.minZ = 0.1;
  99791. //legacy support - the compensation boolean was removed.
  99792. if (arguments.length === 5) {
  99793. _this.webVROptions = arguments[4];
  99794. }
  99795. // default webVR options
  99796. if (_this.webVROptions.trackPosition == undefined) {
  99797. _this.webVROptions.trackPosition = true;
  99798. }
  99799. if (_this.webVROptions.controllerMeshes == undefined) {
  99800. _this.webVROptions.controllerMeshes = true;
  99801. }
  99802. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  99803. _this.webVROptions.defaultLightingOnControllers = true;
  99804. }
  99805. _this.rotationQuaternion = new BABYLON.Quaternion();
  99806. if (_this.webVROptions && _this.webVROptions.positionScale) {
  99807. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  99808. }
  99809. //enable VR
  99810. var engine = _this.getEngine();
  99811. _this._onVREnabled = function (success) { if (success) {
  99812. _this.initControllers();
  99813. } };
  99814. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  99815. engine.initWebVR().add(function (event) {
  99816. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  99817. return;
  99818. }
  99819. _this._vrDevice = event.vrDisplay;
  99820. //reset the rig parameters.
  99821. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  99822. if (_this._attached) {
  99823. _this.getEngine().enableVR();
  99824. }
  99825. });
  99826. if (typeof (VRFrameData) !== "undefined")
  99827. _this._frameData = new VRFrameData();
  99828. /**
  99829. * The idea behind the following lines:
  99830. * objects that have the camera as parent should actually have the rig cameras as a parent.
  99831. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  99832. * the second will not show it correctly.
  99833. *
  99834. * To solve this - each object that has the camera as parent will be added to a protected array.
  99835. * When the rig camera renders, it will take this array and set all of those to be its children.
  99836. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  99837. * Amazing!
  99838. */
  99839. scene.onBeforeCameraRenderObservable.add(function (camera) {
  99840. if (camera.parent === _this && _this.rigParenting) {
  99841. _this._descendants = _this.getDescendants(true, function (n) {
  99842. // don't take the cameras or the controllers!
  99843. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  99844. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  99845. return !isController && !isRigCamera;
  99846. });
  99847. _this._descendants.forEach(function (node) {
  99848. node.parent = camera;
  99849. });
  99850. }
  99851. });
  99852. scene.onAfterCameraRenderObservable.add(function (camera) {
  99853. if (camera.parent === _this && _this.rigParenting) {
  99854. _this._descendants.forEach(function (node) {
  99855. node.parent = _this;
  99856. });
  99857. }
  99858. });
  99859. return _this;
  99860. }
  99861. /**
  99862. * Gets the device distance from the ground in meters.
  99863. * @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.
  99864. */
  99865. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  99866. if (this._standingMatrix) {
  99867. // Add standing matrix offset to get real offset from ground in room
  99868. this._standingMatrix.getTranslationToRef(this._workingVector);
  99869. return this._deviceRoomPosition.y + this._workingVector.y;
  99870. }
  99871. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  99872. return this._defaultHeight || 0;
  99873. };
  99874. /**
  99875. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99876. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  99877. */
  99878. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  99879. var _this = this;
  99880. if (callback === void 0) { callback = function (bool) { }; }
  99881. // Use standing matrix if available
  99882. this.getEngine().initWebVRAsync().then(function (result) {
  99883. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  99884. callback(false);
  99885. }
  99886. else {
  99887. _this._standingMatrix = new BABYLON.Matrix();
  99888. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  99889. if (!_this.getScene().useRightHandedSystem) {
  99890. [2, 6, 8, 9, 14].forEach(function (num) {
  99891. if (_this._standingMatrix) {
  99892. _this._standingMatrix.m[num] *= -1;
  99893. }
  99894. });
  99895. }
  99896. callback(true);
  99897. }
  99898. });
  99899. };
  99900. /**
  99901. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99902. * @returns A promise with a boolean set to if the standing matrix is supported.
  99903. */
  99904. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  99905. var _this = this;
  99906. return new Promise(function (res, rej) {
  99907. _this.useStandingMatrix(function (supported) {
  99908. res(supported);
  99909. });
  99910. });
  99911. };
  99912. /**
  99913. * Disposes the camera
  99914. */
  99915. WebVRFreeCamera.prototype.dispose = function () {
  99916. this._detachIfAttached();
  99917. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  99918. if (this._updateCacheWhenTrackingDisabledObserver) {
  99919. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  99920. }
  99921. _super.prototype.dispose.call(this);
  99922. };
  99923. /**
  99924. * Gets a vrController by name.
  99925. * @param name The name of the controller to retreive
  99926. * @returns the controller matching the name specified or null if not found
  99927. */
  99928. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  99929. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  99930. var gp = _a[_i];
  99931. if (gp.hand === name) {
  99932. return gp;
  99933. }
  99934. }
  99935. return null;
  99936. };
  99937. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  99938. /**
  99939. * The controller corrisponding to the users left hand.
  99940. */
  99941. get: function () {
  99942. if (!this._leftController) {
  99943. this._leftController = this.getControllerByName("left");
  99944. }
  99945. return this._leftController;
  99946. },
  99947. enumerable: true,
  99948. configurable: true
  99949. });
  99950. ;
  99951. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  99952. /**
  99953. * The controller corrisponding to the users right hand.
  99954. */
  99955. get: function () {
  99956. if (!this._rightController) {
  99957. this._rightController = this.getControllerByName("right");
  99958. }
  99959. return this._rightController;
  99960. },
  99961. enumerable: true,
  99962. configurable: true
  99963. });
  99964. ;
  99965. /**
  99966. * Casts a ray forward from the vrCamera's gaze.
  99967. * @param length Length of the ray (default: 100)
  99968. * @returns the ray corrisponding to the gaze
  99969. */
  99970. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  99971. if (length === void 0) { length = 100; }
  99972. if (this.leftCamera) {
  99973. // Use left eye to avoid computation to compute center on every call
  99974. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  99975. }
  99976. else {
  99977. return _super.prototype.getForwardRay.call(this, length);
  99978. }
  99979. };
  99980. /**
  99981. * @hidden
  99982. * Updates the camera based on device's frame data
  99983. */
  99984. WebVRFreeCamera.prototype._checkInputs = function () {
  99985. if (this._vrDevice && this._vrDevice.isPresenting) {
  99986. this._vrDevice.getFrameData(this._frameData);
  99987. this.updateFromDevice(this._frameData.pose);
  99988. }
  99989. _super.prototype._checkInputs.call(this);
  99990. };
  99991. /**
  99992. * Updates the poseControlled values based on the input device pose.
  99993. * @param poseData Pose coming from the device
  99994. */
  99995. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  99996. if (poseData && poseData.orientation) {
  99997. this.rawPose = poseData;
  99998. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  99999. if (this.getScene().useRightHandedSystem) {
  100000. this._deviceRoomRotationQuaternion.z *= -1;
  100001. this._deviceRoomRotationQuaternion.w *= -1;
  100002. }
  100003. if (this.webVROptions.trackPosition && this.rawPose.position) {
  100004. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  100005. if (this.getScene().useRightHandedSystem) {
  100006. this._deviceRoomPosition.z *= -1;
  100007. }
  100008. }
  100009. this._poseSet = true;
  100010. }
  100011. };
  100012. /**
  100013. * WebVR's attach control will start broadcasting frames to the device.
  100014. * Note that in certain browsers (chrome for example) this function must be called
  100015. * within a user-interaction callback. Example:
  100016. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  100017. *
  100018. * @param element html element to attach the vrDevice to
  100019. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  100020. */
  100021. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  100022. _super.prototype.attachControl.call(this, element, noPreventDefault);
  100023. this._attached = true;
  100024. this._htmlElementAttached = element;
  100025. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  100026. if (this._vrDevice) {
  100027. this.getEngine().enableVR();
  100028. }
  100029. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100030. };
  100031. /**
  100032. * Detaches the camera from the html element and disables VR
  100033. *
  100034. * @param element html element to detach from
  100035. */
  100036. WebVRFreeCamera.prototype.detachControl = function (element) {
  100037. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  100038. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  100039. _super.prototype.detachControl.call(this, element);
  100040. this._attached = false;
  100041. this.getEngine().disableVR();
  100042. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100043. };
  100044. /**
  100045. * @returns the name of this class
  100046. */
  100047. WebVRFreeCamera.prototype.getClassName = function () {
  100048. return "WebVRFreeCamera";
  100049. };
  100050. /**
  100051. * Calls resetPose on the vrDisplay
  100052. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  100053. */
  100054. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  100055. //uses the vrDisplay's "resetPose()".
  100056. //pitch and roll won't be affected.
  100057. this._vrDevice.resetPose();
  100058. };
  100059. /**
  100060. * @hidden
  100061. * Updates the rig cameras (left and right eye)
  100062. */
  100063. WebVRFreeCamera.prototype._updateRigCameras = function () {
  100064. var camLeft = this._rigCameras[0];
  100065. var camRight = this._rigCameras[1];
  100066. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100067. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100068. camLeft.position.copyFrom(this._deviceRoomPosition);
  100069. camRight.position.copyFrom(this._deviceRoomPosition);
  100070. };
  100071. // Remove translation from 6dof headset if trackposition is set to false
  100072. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  100073. if (isViewMatrix === void 0) { isViewMatrix = false; }
  100074. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  100075. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  100076. if (!isViewMatrix) {
  100077. this._tmpMatrix.invert();
  100078. }
  100079. this._tmpMatrix.multiplyToRef(matrix, matrix);
  100080. }
  100081. };
  100082. /**
  100083. * @hidden
  100084. * Updates the cached values of the camera
  100085. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  100086. */
  100087. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  100088. var _this = this;
  100089. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  100090. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  100091. if (!this.updateCacheCalled) {
  100092. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  100093. this.updateCacheCalled = true;
  100094. this.update();
  100095. }
  100096. // Set working vector to the device position in room space rotated by the new rotation
  100097. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  100098. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  100099. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  100100. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  100101. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  100102. // Add translation from anchor position
  100103. this._deviceToWorld.getTranslationToRef(this._workingVector);
  100104. this._workingVector.addInPlace(this.position);
  100105. this._workingVector.subtractInPlace(this._cache.position);
  100106. this._deviceToWorld.setTranslation(this._workingVector);
  100107. // Set an inverted matrix to be used when updating the camera
  100108. this._deviceToWorld.invertToRef(this._worldToDevice);
  100109. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  100110. this.controllers.forEach(function (controller) {
  100111. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  100112. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  100113. controller.update();
  100114. });
  100115. }
  100116. if (!ignoreParentClass) {
  100117. _super.prototype._updateCache.call(this);
  100118. }
  100119. this.updateCacheCalled = false;
  100120. };
  100121. /**
  100122. * @hidden
  100123. * Get current device position in babylon world
  100124. */
  100125. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  100126. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  100127. };
  100128. /**
  100129. * Updates the current device position and rotation in the babylon world
  100130. */
  100131. WebVRFreeCamera.prototype.update = function () {
  100132. this._computeDevicePosition();
  100133. // Get current device rotation in babylon world
  100134. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  100135. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  100136. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  100137. if (this._poseSet) {
  100138. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  100139. }
  100140. _super.prototype.update.call(this);
  100141. };
  100142. /**
  100143. * @hidden
  100144. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  100145. * @returns an identity matrix
  100146. */
  100147. WebVRFreeCamera.prototype._getViewMatrix = function () {
  100148. return BABYLON.Matrix.Identity();
  100149. };
  100150. /**
  100151. * This function is called by the two RIG cameras.
  100152. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  100153. */
  100154. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  100155. var _this = this;
  100156. // Update the parent camera prior to using a child camera to avoid desynchronization
  100157. var parentCamera = this._cameraRigParams["parentCamera"];
  100158. parentCamera._updateCache();
  100159. //WebVR 1.1
  100160. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  100161. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  100162. if (!this.getScene().useRightHandedSystem) {
  100163. [2, 6, 8, 9, 14].forEach(function (num) {
  100164. _this._webvrViewMatrix.m[num] *= -1;
  100165. });
  100166. }
  100167. // update the camera rotation matrix
  100168. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  100169. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  100170. // Computing target and final matrix
  100171. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  100172. // should the view matrix be updated with scale and position offset?
  100173. if (parentCamera.deviceScaleFactor !== 1) {
  100174. this._webvrViewMatrix.invert();
  100175. // scale the position, if set
  100176. if (parentCamera.deviceScaleFactor) {
  100177. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  100178. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  100179. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  100180. }
  100181. this._webvrViewMatrix.invert();
  100182. }
  100183. // Remove translation from 6dof headset if trackposition is set to false
  100184. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  100185. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  100186. // Compute global position
  100187. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  100188. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  100189. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  100190. this._workingMatrix.getTranslationToRef(this._globalPosition);
  100191. this._markSyncedWithParent();
  100192. return this._webvrViewMatrix;
  100193. };
  100194. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  100195. var _this = this;
  100196. var parentCamera = this.parent;
  100197. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  100198. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  100199. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  100200. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  100201. //babylon compatible matrix
  100202. if (!this.getScene().useRightHandedSystem) {
  100203. [8, 9, 10, 11].forEach(function (num) {
  100204. _this._projectionMatrix.m[num] *= -1;
  100205. });
  100206. }
  100207. return this._projectionMatrix;
  100208. };
  100209. /**
  100210. * Initializes the controllers and their meshes
  100211. */
  100212. WebVRFreeCamera.prototype.initControllers = function () {
  100213. var _this = this;
  100214. this.controllers = [];
  100215. var manager = this.getScene().gamepadManager;
  100216. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  100217. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100218. var webVrController = gamepad;
  100219. if (webVrController.defaultModel) {
  100220. webVrController.defaultModel.setEnabled(false);
  100221. }
  100222. if (webVrController.hand === "right") {
  100223. _this._rightController = null;
  100224. }
  100225. if (webVrController.hand === "left") {
  100226. _this._leftController = null;
  100227. }
  100228. var controllerIndex = _this.controllers.indexOf(webVrController);
  100229. if (controllerIndex !== -1) {
  100230. _this.controllers.splice(controllerIndex, 1);
  100231. }
  100232. }
  100233. });
  100234. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  100235. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100236. var webVrController_1 = gamepad;
  100237. if (!_this.webVROptions.trackPosition) {
  100238. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  100239. // Cache must be updated before rendering controllers to avoid them being one frame behind
  100240. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  100241. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  100242. _this._updateCache();
  100243. });
  100244. }
  100245. }
  100246. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  100247. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  100248. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  100249. if (_this.webVROptions.controllerMeshes) {
  100250. if (webVrController_1.defaultModel) {
  100251. webVrController_1.defaultModel.setEnabled(true);
  100252. }
  100253. else {
  100254. // Load the meshes
  100255. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  100256. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  100257. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  100258. if (_this.webVROptions.defaultLightingOnControllers) {
  100259. if (!_this._lightOnControllers) {
  100260. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  100261. }
  100262. var activateLightOnSubMeshes_1 = function (mesh, light) {
  100263. var children = mesh.getChildren();
  100264. if (children && children.length !== 0) {
  100265. children.forEach(function (mesh) {
  100266. light.includedOnlyMeshes.push(mesh);
  100267. activateLightOnSubMeshes_1(mesh, light);
  100268. });
  100269. }
  100270. };
  100271. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  100272. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  100273. }
  100274. });
  100275. }
  100276. }
  100277. webVrController_1.attachToPoseControlledCamera(_this);
  100278. // since this is async - sanity check. Is the controller already stored?
  100279. if (_this.controllers.indexOf(webVrController_1) === -1) {
  100280. //add to the controllers array
  100281. _this.controllers.push(webVrController_1);
  100282. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  100283. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  100284. // So we're overriding setting left & right manually to be sure
  100285. var firstViveWandDetected = false;
  100286. for (var i = 0; i < _this.controllers.length; i++) {
  100287. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100288. if (!firstViveWandDetected) {
  100289. firstViveWandDetected = true;
  100290. _this.controllers[i].hand = "left";
  100291. }
  100292. else {
  100293. _this.controllers[i].hand = "right";
  100294. }
  100295. }
  100296. }
  100297. //did we find enough controllers? Great! let the developer know.
  100298. if (_this.controllers.length >= 2) {
  100299. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  100300. }
  100301. }
  100302. }
  100303. });
  100304. };
  100305. return WebVRFreeCamera;
  100306. }(BABYLON.FreeCamera));
  100307. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  100308. })(BABYLON || (BABYLON = {}));
  100309. //# sourceMappingURL=babylon.webVRCamera.js.map
  100310. var BABYLON;
  100311. (function (BABYLON) {
  100312. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  100313. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  100314. });
  100315. // We're mainly based on the logic defined into the FreeCamera code
  100316. /**
  100317. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  100318. * being tilted forward or back and left or right.
  100319. */
  100320. var DeviceOrientationCamera = /** @class */ (function (_super) {
  100321. __extends(DeviceOrientationCamera, _super);
  100322. /**
  100323. * Creates a new device orientation camera
  100324. * @param name The name of the camera
  100325. * @param position The start position camera
  100326. * @param scene The scene the camera belongs to
  100327. */
  100328. function DeviceOrientationCamera(name, position, scene) {
  100329. var _this = _super.call(this, name, position, scene) || this;
  100330. _this._quaternionCache = new BABYLON.Quaternion();
  100331. _this.inputs.addDeviceOrientation();
  100332. return _this;
  100333. }
  100334. /**
  100335. * Gets the current instance class name ("DeviceOrientationCamera").
  100336. * This helps avoiding instanceof at run time.
  100337. * @returns the class name
  100338. */
  100339. DeviceOrientationCamera.prototype.getClassName = function () {
  100340. return "DeviceOrientationCamera";
  100341. };
  100342. /**
  100343. * @hidden
  100344. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  100345. */
  100346. DeviceOrientationCamera.prototype._checkInputs = function () {
  100347. _super.prototype._checkInputs.call(this);
  100348. this._quaternionCache.copyFrom(this.rotationQuaternion);
  100349. if (this._initialQuaternion) {
  100350. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100351. }
  100352. };
  100353. /**
  100354. * Reset the camera to its default orientation on the specified axis only.
  100355. * @param axis The axis to reset
  100356. */
  100357. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  100358. var _this = this;
  100359. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  100360. //can only work if this camera has a rotation quaternion already.
  100361. if (!this.rotationQuaternion)
  100362. return;
  100363. if (!this._initialQuaternion) {
  100364. this._initialQuaternion = new BABYLON.Quaternion();
  100365. }
  100366. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  100367. ['x', 'y', 'z'].forEach(function (axisName) {
  100368. if (!axis[axisName]) {
  100369. _this._initialQuaternion[axisName] = 0;
  100370. }
  100371. else {
  100372. _this._initialQuaternion[axisName] *= -1;
  100373. }
  100374. });
  100375. this._initialQuaternion.normalize();
  100376. //force rotation update
  100377. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100378. };
  100379. return DeviceOrientationCamera;
  100380. }(BABYLON.FreeCamera));
  100381. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  100382. })(BABYLON || (BABYLON = {}));
  100383. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  100384. var BABYLON;
  100385. (function (BABYLON) {
  100386. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100387. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100388. });
  100389. /**
  100390. * Camera used to simulate VR rendering (based on FreeCamera)
  100391. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100392. */
  100393. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  100394. __extends(VRDeviceOrientationFreeCamera, _super);
  100395. /**
  100396. * Creates a new VRDeviceOrientationFreeCamera
  100397. * @param name defines camera name
  100398. * @param position defines the start position of the camera
  100399. * @param scene defines the scene the camera belongs to
  100400. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100401. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100402. */
  100403. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100404. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100405. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100406. var _this = _super.call(this, name, position, scene) || this;
  100407. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100408. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100409. return _this;
  100410. }
  100411. /**
  100412. * Gets camera class name
  100413. * @returns VRDeviceOrientationFreeCamera
  100414. */
  100415. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  100416. return "VRDeviceOrientationFreeCamera";
  100417. };
  100418. return VRDeviceOrientationFreeCamera;
  100419. }(BABYLON.DeviceOrientationCamera));
  100420. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  100421. })(BABYLON || (BABYLON = {}));
  100422. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  100423. var BABYLON;
  100424. (function (BABYLON) {
  100425. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100426. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  100427. });
  100428. /**
  100429. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  100430. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100431. */
  100432. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  100433. __extends(VRDeviceOrientationArcRotateCamera, _super);
  100434. /**
  100435. * Creates a new VRDeviceOrientationArcRotateCamera
  100436. * @param name defines camera name
  100437. * @param alpha defines the camera rotation along the logitudinal axis
  100438. * @param beta defines the camera rotation along the latitudinal axis
  100439. * @param radius defines the camera distance from its target
  100440. * @param target defines the camera target
  100441. * @param scene defines the scene the camera belongs to
  100442. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100443. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100444. */
  100445. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  100446. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100447. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100448. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100449. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100450. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100451. _this.inputs.addVRDeviceOrientation();
  100452. return _this;
  100453. }
  100454. /**
  100455. * Gets camera class name
  100456. * @returns VRDeviceOrientationArcRotateCamera
  100457. */
  100458. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  100459. return "VRDeviceOrientationArcRotateCamera";
  100460. };
  100461. return VRDeviceOrientationArcRotateCamera;
  100462. }(BABYLON.ArcRotateCamera));
  100463. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  100464. })(BABYLON || (BABYLON = {}));
  100465. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  100466. var BABYLON;
  100467. (function (BABYLON) {
  100468. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  100469. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  100470. });
  100471. /**
  100472. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  100473. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100474. */
  100475. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  100476. __extends(VRDeviceOrientationGamepadCamera, _super);
  100477. /**
  100478. * Creates a new VRDeviceOrientationGamepadCamera
  100479. * @param name defines camera name
  100480. * @param position defines the start position of the camera
  100481. * @param scene defines the scene the camera belongs to
  100482. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100483. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100484. */
  100485. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100486. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100487. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100488. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  100489. _this.inputs.addGamepad();
  100490. return _this;
  100491. }
  100492. /**
  100493. * Gets camera class name
  100494. * @returns VRDeviceOrientationGamepadCamera
  100495. */
  100496. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  100497. return "VRDeviceOrientationGamepadCamera";
  100498. };
  100499. return VRDeviceOrientationGamepadCamera;
  100500. }(BABYLON.VRDeviceOrientationFreeCamera));
  100501. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  100502. })(BABYLON || (BABYLON = {}));
  100503. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  100504. var BABYLON;
  100505. (function (BABYLON) {
  100506. var VRExperienceHelperGazer = /** @class */ (function () {
  100507. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  100508. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  100509. this.scene = scene;
  100510. /** @hidden */
  100511. this._pointerDownOnMeshAsked = false;
  100512. /** @hidden */
  100513. this._isActionableMesh = false;
  100514. /** @hidden */
  100515. this._teleportationRequestInitiated = false;
  100516. /** @hidden */
  100517. this._teleportationBackRequestInitiated = false;
  100518. /** @hidden */
  100519. this._rotationRightAsked = false;
  100520. /** @hidden */
  100521. this._rotationLeftAsked = false;
  100522. /** @hidden */
  100523. this._dpadPressed = true;
  100524. /** @hidden */
  100525. this._activePointer = false;
  100526. this._id = VRExperienceHelperGazer._idCounter++;
  100527. // Gaze tracker
  100528. if (!gazeTrackerToClone) {
  100529. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  100530. this._gazeTracker.bakeCurrentTransformIntoVertices();
  100531. this._gazeTracker.isPickable = false;
  100532. this._gazeTracker.isVisible = false;
  100533. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  100534. targetMat.specularColor = BABYLON.Color3.Black();
  100535. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100536. targetMat.backFaceCulling = false;
  100537. this._gazeTracker.material = targetMat;
  100538. }
  100539. else {
  100540. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  100541. }
  100542. }
  100543. /** @hidden */
  100544. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  100545. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  100546. };
  100547. /** @hidden */
  100548. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  100549. this._pointerDownOnMeshAsked = true;
  100550. if (this._currentHit) {
  100551. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  100552. }
  100553. };
  100554. /** @hidden */
  100555. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  100556. if (this._currentHit) {
  100557. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  100558. }
  100559. this._pointerDownOnMeshAsked = false;
  100560. };
  100561. /** @hidden */
  100562. VRExperienceHelperGazer.prototype._activatePointer = function () {
  100563. this._activePointer = true;
  100564. };
  100565. /** @hidden */
  100566. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  100567. this._activePointer = false;
  100568. };
  100569. /** @hidden */
  100570. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  100571. if (distance === void 0) { distance = 100; }
  100572. };
  100573. VRExperienceHelperGazer.prototype.dispose = function () {
  100574. this._interactionsEnabled = false;
  100575. this._teleportationEnabled = false;
  100576. if (this._gazeTracker) {
  100577. this._gazeTracker.dispose();
  100578. }
  100579. };
  100580. VRExperienceHelperGazer._idCounter = 0;
  100581. return VRExperienceHelperGazer;
  100582. }());
  100583. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  100584. __extends(VRExperienceHelperControllerGazer, _super);
  100585. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  100586. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  100587. _this.webVRController = webVRController;
  100588. // Laser pointer
  100589. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  100590. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  100591. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100592. laserPointerMaterial.alpha = 0.6;
  100593. _this._laserPointer.material = laserPointerMaterial;
  100594. _this._laserPointer.rotation.x = Math.PI / 2;
  100595. _this._laserPointer.position.z = -0.5;
  100596. _this._laserPointer.isVisible = false;
  100597. _this._laserPointer.isPickable = false;
  100598. if (!webVRController.mesh) {
  100599. // Create an empty mesh that is used prior to loading the high quality model
  100600. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  100601. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  100602. preloadPointerPose.rotation.x = -0.7;
  100603. preloadMesh.addChild(preloadPointerPose);
  100604. webVRController.attachToMesh(preloadMesh);
  100605. }
  100606. _this._setLaserPointerParent(webVRController.mesh);
  100607. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  100608. _this._setLaserPointerParent(mesh);
  100609. });
  100610. return _this;
  100611. }
  100612. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  100613. return this.webVRController.getForwardRay(length);
  100614. };
  100615. /** @hidden */
  100616. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  100617. _super.prototype._activatePointer.call(this);
  100618. this._laserPointer.isVisible = true;
  100619. };
  100620. /** @hidden */
  100621. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  100622. _super.prototype._deactivatePointer.call(this);
  100623. this._laserPointer.isVisible = false;
  100624. };
  100625. /** @hidden */
  100626. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  100627. this._laserPointer.material.emissiveColor = color;
  100628. };
  100629. /** @hidden */
  100630. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  100631. var makeNotPick = function (root) {
  100632. root.isPickable = false;
  100633. root.getChildMeshes().forEach(function (c) {
  100634. makeNotPick(c);
  100635. });
  100636. };
  100637. makeNotPick(mesh);
  100638. var childMeshes = mesh.getChildMeshes();
  100639. this.webVRController._pointingPoseNode = null;
  100640. for (var i = 0; i < childMeshes.length; i++) {
  100641. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  100642. mesh = childMeshes[i];
  100643. this.webVRController._pointingPoseNode = mesh;
  100644. break;
  100645. }
  100646. }
  100647. this._laserPointer.parent = mesh;
  100648. };
  100649. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  100650. if (distance === void 0) { distance = 100; }
  100651. this._laserPointer.scaling.y = distance;
  100652. this._laserPointer.position.z = -distance / 2;
  100653. };
  100654. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  100655. _super.prototype.dispose.call(this);
  100656. this._laserPointer.dispose();
  100657. if (this._meshAttachedObserver) {
  100658. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  100659. }
  100660. };
  100661. return VRExperienceHelperControllerGazer;
  100662. }(VRExperienceHelperGazer));
  100663. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  100664. __extends(VRExperienceHelperCameraGazer, _super);
  100665. function VRExperienceHelperCameraGazer(getCamera, scene) {
  100666. var _this = _super.call(this, scene) || this;
  100667. _this.getCamera = getCamera;
  100668. return _this;
  100669. }
  100670. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  100671. var camera = this.getCamera();
  100672. if (camera) {
  100673. return camera.getForwardRay(length);
  100674. }
  100675. else {
  100676. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  100677. }
  100678. };
  100679. return VRExperienceHelperCameraGazer;
  100680. }(VRExperienceHelperGazer));
  100681. /**
  100682. * Helps to quickly add VR support to an existing scene.
  100683. * See http://doc.babylonjs.com/how_to/webvr_helper
  100684. */
  100685. var VRExperienceHelper = /** @class */ (function () {
  100686. /**
  100687. * Instantiates a VRExperienceHelper.
  100688. * Helps to quickly add VR support to an existing scene.
  100689. * @param scene The scene the VRExperienceHelper belongs to.
  100690. * @param webVROptions Options to modify the vr experience helper's behavior.
  100691. */
  100692. function VRExperienceHelper(scene,
  100693. /** Options to modify the vr experience helper's behavior. */
  100694. webVROptions) {
  100695. if (webVROptions === void 0) { webVROptions = {}; }
  100696. var _this = this;
  100697. this.webVROptions = webVROptions;
  100698. // Can the system support WebVR, even if a headset isn't plugged in?
  100699. this._webVRsupported = false;
  100700. // If WebVR is supported, is a headset plugged in and are we ready to present?
  100701. this._webVRready = false;
  100702. // Are we waiting for the requestPresent callback to complete?
  100703. this._webVRrequesting = false;
  100704. // Are we presenting to the headset right now? (this is the vrDevice state)
  100705. this._webVRpresenting = false;
  100706. // Are we presenting in the fullscreen fallback?
  100707. this._fullscreenVRpresenting = false;
  100708. /**
  100709. * Observable raised when entering VR.
  100710. */
  100711. this.onEnteringVRObservable = new BABYLON.Observable();
  100712. /**
  100713. * Observable raised when exiting VR.
  100714. */
  100715. this.onExitingVRObservable = new BABYLON.Observable();
  100716. /**
  100717. * Observable raised when controller mesh is loaded.
  100718. */
  100719. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100720. this._useCustomVRButton = false;
  100721. this._teleportationRequested = false;
  100722. this._teleportActive = false;
  100723. this._floorMeshesCollection = [];
  100724. this._rotationAllowed = true;
  100725. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  100726. this._isDefaultTeleportationTarget = true;
  100727. this._teleportationFillColor = "#444444";
  100728. this._teleportationBorderColor = "#FFFFFF";
  100729. this._rotationAngle = 0;
  100730. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  100731. this._padSensibilityUp = 0.65;
  100732. this._padSensibilityDown = 0.35;
  100733. this._leftController = null;
  100734. this._rightController = null;
  100735. /**
  100736. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  100737. */
  100738. this.onNewMeshSelected = new BABYLON.Observable();
  100739. /**
  100740. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  100741. */
  100742. this.onNewMeshPicked = new BABYLON.Observable();
  100743. /**
  100744. * Observable raised before camera teleportation
  100745. */
  100746. this.onBeforeCameraTeleport = new BABYLON.Observable();
  100747. /**
  100748. * Observable raised after camera teleportation
  100749. */
  100750. this.onAfterCameraTeleport = new BABYLON.Observable();
  100751. /**
  100752. * Observable raised when current selected mesh gets unselected
  100753. */
  100754. this.onSelectedMeshUnselected = new BABYLON.Observable();
  100755. /**
  100756. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  100757. */
  100758. this.teleportationEnabled = true;
  100759. this._teleportationInitialized = false;
  100760. this._interactionsEnabled = false;
  100761. this._interactionsRequested = false;
  100762. this._displayGaze = true;
  100763. this._displayLaserPointer = true;
  100764. /**
  100765. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  100766. */
  100767. this.updateGazeTrackerScale = true;
  100768. this._onResize = function () {
  100769. _this.moveButtonToBottomRight();
  100770. if (_this._fullscreenVRpresenting && _this._webVRready) {
  100771. _this.exitVR();
  100772. }
  100773. };
  100774. this._onFullscreenChange = function () {
  100775. if (document.fullscreen !== undefined) {
  100776. _this._fullscreenVRpresenting = document.fullscreen;
  100777. }
  100778. else if (document.mozFullScreen !== undefined) {
  100779. _this._fullscreenVRpresenting = document.mozFullScreen;
  100780. }
  100781. else if (document.webkitIsFullScreen !== undefined) {
  100782. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  100783. }
  100784. else if (document.msIsFullScreen !== undefined) {
  100785. _this._fullscreenVRpresenting = document.msIsFullScreen;
  100786. }
  100787. else if (document.msFullscreenElement !== undefined) {
  100788. _this._fullscreenVRpresenting = document.msFullscreenElement;
  100789. }
  100790. if (!_this._fullscreenVRpresenting && _this._canvas) {
  100791. _this.exitVR();
  100792. if (!_this._useCustomVRButton) {
  100793. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  100794. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  100795. }
  100796. }
  100797. };
  100798. this.beforeRender = function () {
  100799. if (_this._leftController && _this._leftController._activePointer) {
  100800. _this._castRayAndSelectObject(_this._leftController);
  100801. }
  100802. if (_this._rightController && _this._rightController._activePointer) {
  100803. _this._castRayAndSelectObject(_this._rightController);
  100804. }
  100805. if (_this._noControllerIsActive) {
  100806. _this._castRayAndSelectObject(_this._cameraGazer);
  100807. }
  100808. else {
  100809. _this._cameraGazer._gazeTracker.isVisible = false;
  100810. }
  100811. };
  100812. this._onNewGamepadConnected = function (gamepad) {
  100813. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  100814. if (gamepad.leftStick) {
  100815. gamepad.onleftstickchanged(function (stickValues) {
  100816. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  100817. // Listening to classic/xbox gamepad only if no VR controller is active
  100818. if ((!_this._leftController && !_this._rightController) ||
  100819. ((_this._leftController && !_this._leftController._activePointer) &&
  100820. (_this._rightController && !_this._rightController._activePointer))) {
  100821. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  100822. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  100823. }
  100824. }
  100825. });
  100826. }
  100827. if (gamepad.rightStick) {
  100828. gamepad.onrightstickchanged(function (stickValues) {
  100829. if (_this._teleportationInitialized) {
  100830. _this._checkRotate(stickValues, _this._cameraGazer);
  100831. }
  100832. });
  100833. }
  100834. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  100835. gamepad.onbuttondown(function (buttonPressed) {
  100836. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100837. _this._cameraGazer._selectionPointerDown();
  100838. }
  100839. });
  100840. gamepad.onbuttonup(function (buttonPressed) {
  100841. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100842. _this._cameraGazer._selectionPointerUp();
  100843. }
  100844. });
  100845. }
  100846. }
  100847. else {
  100848. var webVRController = gamepad;
  100849. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  100850. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  100851. _this._rightController = controller;
  100852. }
  100853. else {
  100854. _this._leftController = controller;
  100855. }
  100856. _this._tryEnableInteractionOnController(controller);
  100857. }
  100858. };
  100859. // 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
  100860. this._tryEnableInteractionOnController = function (controller) {
  100861. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  100862. _this._enableInteractionOnController(controller);
  100863. }
  100864. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  100865. _this._enableTeleportationOnController(controller);
  100866. }
  100867. };
  100868. this._onNewGamepadDisconnected = function (gamepad) {
  100869. if (gamepad instanceof BABYLON.WebVRController) {
  100870. if (gamepad.hand === "left" && _this._leftController != null) {
  100871. _this._leftController.dispose();
  100872. _this._leftController = null;
  100873. }
  100874. if (gamepad.hand === "right" && _this._rightController != null) {
  100875. _this._rightController.dispose();
  100876. _this._rightController = null;
  100877. }
  100878. }
  100879. };
  100880. this._workingVector = BABYLON.Vector3.Zero();
  100881. this._workingQuaternion = BABYLON.Quaternion.Identity();
  100882. this._workingMatrix = BABYLON.Matrix.Identity();
  100883. this._scene = scene;
  100884. this._canvas = scene.getEngine().getRenderingCanvas();
  100885. // Parse options
  100886. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  100887. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  100888. }
  100889. if (webVROptions.createDeviceOrientationCamera === undefined) {
  100890. webVROptions.createDeviceOrientationCamera = true;
  100891. }
  100892. if (webVROptions.laserToggle === undefined) {
  100893. webVROptions.laserToggle = true;
  100894. }
  100895. if (webVROptions.defaultHeight === undefined) {
  100896. webVROptions.defaultHeight = 1.7;
  100897. }
  100898. if (webVROptions.useCustomVRButton) {
  100899. this._useCustomVRButton = true;
  100900. if (webVROptions.customVRButton) {
  100901. this._btnVR = webVROptions.customVRButton;
  100902. }
  100903. }
  100904. if (webVROptions.rayLength) {
  100905. this._rayLength = webVROptions.rayLength;
  100906. }
  100907. this._defaultHeight = webVROptions.defaultHeight;
  100908. if (webVROptions.positionScale) {
  100909. this._rayLength *= webVROptions.positionScale;
  100910. this._defaultHeight *= webVROptions.positionScale;
  100911. }
  100912. this._hasEnteredVR = false;
  100913. // Set position
  100914. if (this._scene.activeCamera) {
  100915. this._position = this._scene.activeCamera.position.clone();
  100916. }
  100917. else {
  100918. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  100919. }
  100920. // Set non-vr camera
  100921. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  100922. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  100923. // Copy data from existing camera
  100924. if (this._scene.activeCamera) {
  100925. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100926. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  100927. // Set rotation from previous camera
  100928. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  100929. var targetCamera = this._scene.activeCamera;
  100930. if (targetCamera.rotationQuaternion) {
  100931. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  100932. }
  100933. else {
  100934. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  100935. }
  100936. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  100937. }
  100938. }
  100939. this._scene.activeCamera = this._deviceOrientationCamera;
  100940. if (this._canvas) {
  100941. this._scene.activeCamera.attachControl(this._canvas);
  100942. }
  100943. }
  100944. else {
  100945. this._existingCamera = this._scene.activeCamera;
  100946. }
  100947. // Create VR cameras
  100948. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100949. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  100950. }
  100951. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  100952. this._webVRCamera.useStandingMatrix();
  100953. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  100954. // Create default button
  100955. if (!this._useCustomVRButton) {
  100956. this._btnVR = document.createElement("BUTTON");
  100957. this._btnVR.className = "babylonVRicon";
  100958. this._btnVR.id = "babylonVRiconbtn";
  100959. this._btnVR.title = "Click to switch to VR";
  100960. 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) }";
  100961. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  100962. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  100963. // css += ".babylonVRicon.vrdisplaysupported { }";
  100964. // css += ".babylonVRicon.vrdisplayready { }";
  100965. // css += ".babylonVRicon.vrdisplayrequesting { }";
  100966. var style = document.createElement('style');
  100967. style.appendChild(document.createTextNode(css));
  100968. document.getElementsByTagName('head')[0].appendChild(style);
  100969. this.moveButtonToBottomRight();
  100970. }
  100971. // VR button click event
  100972. if (this._btnVR) {
  100973. this._btnVR.addEventListener("click", function () {
  100974. if (!_this.isInVRMode) {
  100975. _this.enterVR();
  100976. }
  100977. else {
  100978. _this.exitVR();
  100979. }
  100980. });
  100981. }
  100982. // Window events
  100983. window.addEventListener("resize", this._onResize);
  100984. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  100985. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  100986. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  100987. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  100988. document.onmsfullscreenchange = this._onFullscreenChange;
  100989. // Display vr button when headset is connected
  100990. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100991. this.displayVRButton();
  100992. }
  100993. else {
  100994. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  100995. if (e.vrDisplay) {
  100996. _this.displayVRButton();
  100997. }
  100998. });
  100999. }
  101000. // Exiting VR mode using 'ESC' key on desktop
  101001. this._onKeyDown = function (event) {
  101002. if (event.keyCode === 27 && _this.isInVRMode) {
  101003. _this.exitVR();
  101004. }
  101005. };
  101006. document.addEventListener("keydown", this._onKeyDown);
  101007. // Exiting VR mode double tapping the touch screen
  101008. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  101009. if (_this.isInVRMode) {
  101010. _this.exitVR();
  101011. if (_this._fullscreenVRpresenting) {
  101012. _this._scene.getEngine().switchFullscreen(true);
  101013. }
  101014. }
  101015. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  101016. // Listen for WebVR display changes
  101017. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  101018. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  101019. this._onVRRequestPresentStart = function () {
  101020. _this._webVRrequesting = true;
  101021. _this.updateButtonVisibility();
  101022. };
  101023. this._onVRRequestPresentComplete = function (success) {
  101024. _this._webVRrequesting = false;
  101025. _this.updateButtonVisibility();
  101026. };
  101027. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  101028. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  101029. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  101030. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101031. scene.onDisposeObservable.add(function () {
  101032. _this.dispose();
  101033. });
  101034. // Gamepad connection events
  101035. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  101036. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  101037. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  101038. this.updateButtonVisibility();
  101039. //create easing functions
  101040. this._circleEase = new BABYLON.CircleEase();
  101041. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101042. if (this.webVROptions.floorMeshes) {
  101043. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  101044. }
  101045. }
  101046. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  101047. /** Return this.onEnteringVRObservable
  101048. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  101049. */
  101050. get: function () {
  101051. return this.onEnteringVRObservable;
  101052. },
  101053. enumerable: true,
  101054. configurable: true
  101055. });
  101056. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  101057. /** Return this.onExitingVRObservable
  101058. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  101059. */
  101060. get: function () {
  101061. return this.onExitingVRObservable;
  101062. },
  101063. enumerable: true,
  101064. configurable: true
  101065. });
  101066. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  101067. /** Return this.onControllerMeshLoadedObservable
  101068. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  101069. */
  101070. get: function () {
  101071. return this.onControllerMeshLoadedObservable;
  101072. },
  101073. enumerable: true,
  101074. configurable: true
  101075. });
  101076. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  101077. /**
  101078. * The mesh used to display where the user is going to teleport.
  101079. */
  101080. get: function () {
  101081. return this._teleportationTarget;
  101082. },
  101083. /**
  101084. * Sets the mesh to be used to display where the user is going to teleport.
  101085. */
  101086. set: function (value) {
  101087. if (value) {
  101088. value.name = "teleportationTarget";
  101089. this._isDefaultTeleportationTarget = false;
  101090. this._teleportationTarget = value;
  101091. }
  101092. },
  101093. enumerable: true,
  101094. configurable: true
  101095. });
  101096. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  101097. /**
  101098. * 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
  101099. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  101100. * See http://doc.babylonjs.com/resources/baking_transformations
  101101. */
  101102. get: function () {
  101103. return this._cameraGazer._gazeTracker;
  101104. },
  101105. set: function (value) {
  101106. if (value) {
  101107. // Dispose of existing meshes
  101108. if (this._cameraGazer._gazeTracker) {
  101109. this._cameraGazer._gazeTracker.dispose();
  101110. }
  101111. if (this._leftController && this._leftController._gazeTracker) {
  101112. this._leftController._gazeTracker.dispose();
  101113. }
  101114. if (this._rightController && this._rightController._gazeTracker) {
  101115. this._rightController._gazeTracker.dispose();
  101116. }
  101117. // Set and create gaze trackers on head and controllers
  101118. this._cameraGazer._gazeTracker = value;
  101119. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  101120. this._cameraGazer._gazeTracker.isPickable = false;
  101121. this._cameraGazer._gazeTracker.isVisible = false;
  101122. this._cameraGazer._gazeTracker.name = "gazeTracker";
  101123. if (this._leftController) {
  101124. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101125. }
  101126. if (this._rightController) {
  101127. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101128. }
  101129. }
  101130. },
  101131. enumerable: true,
  101132. configurable: true
  101133. });
  101134. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  101135. /**
  101136. * The gaze tracking mesh corresponding to the left controller
  101137. */
  101138. get: function () {
  101139. if (this._leftController) {
  101140. return this._leftController._gazeTracker;
  101141. }
  101142. return null;
  101143. },
  101144. enumerable: true,
  101145. configurable: true
  101146. });
  101147. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  101148. /**
  101149. * The gaze tracking mesh corresponding to the right controller
  101150. */
  101151. get: function () {
  101152. if (this._rightController) {
  101153. return this._rightController._gazeTracker;
  101154. }
  101155. return null;
  101156. },
  101157. enumerable: true,
  101158. configurable: true
  101159. });
  101160. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  101161. /**
  101162. * If the ray of the gaze should be displayed.
  101163. */
  101164. get: function () {
  101165. return this._displayGaze;
  101166. },
  101167. /**
  101168. * Sets if the ray of the gaze should be displayed.
  101169. */
  101170. set: function (value) {
  101171. this._displayGaze = value;
  101172. if (!value) {
  101173. this._cameraGazer._gazeTracker.isVisible = false;
  101174. if (this._leftController) {
  101175. this._leftController._gazeTracker.isVisible = false;
  101176. }
  101177. if (this._rightController) {
  101178. this._rightController._gazeTracker.isVisible = false;
  101179. }
  101180. }
  101181. },
  101182. enumerable: true,
  101183. configurable: true
  101184. });
  101185. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  101186. /**
  101187. * If the ray of the LaserPointer should be displayed.
  101188. */
  101189. get: function () {
  101190. return this._displayLaserPointer;
  101191. },
  101192. /**
  101193. * Sets if the ray of the LaserPointer should be displayed.
  101194. */
  101195. set: function (value) {
  101196. this._displayLaserPointer = value;
  101197. if (!value) {
  101198. if (this._rightController) {
  101199. this._rightController._deactivatePointer();
  101200. this._rightController._gazeTracker.isVisible = false;
  101201. }
  101202. if (this._leftController) {
  101203. this._leftController._deactivatePointer();
  101204. this._leftController._gazeTracker.isVisible = false;
  101205. }
  101206. }
  101207. else {
  101208. if (this._rightController) {
  101209. this._rightController._activatePointer();
  101210. }
  101211. if (this._leftController) {
  101212. this._leftController._activatePointer();
  101213. }
  101214. }
  101215. },
  101216. enumerable: true,
  101217. configurable: true
  101218. });
  101219. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  101220. /**
  101221. * The deviceOrientationCamera used as the camera when not in VR.
  101222. */
  101223. get: function () {
  101224. return this._deviceOrientationCamera;
  101225. },
  101226. enumerable: true,
  101227. configurable: true
  101228. });
  101229. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  101230. /**
  101231. * Based on the current WebVR support, returns the current VR camera used.
  101232. */
  101233. get: function () {
  101234. if (this._webVRready) {
  101235. return this._webVRCamera;
  101236. }
  101237. else {
  101238. return this._scene.activeCamera;
  101239. }
  101240. },
  101241. enumerable: true,
  101242. configurable: true
  101243. });
  101244. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  101245. /**
  101246. * The webVRCamera which is used when in VR.
  101247. */
  101248. get: function () {
  101249. return this._webVRCamera;
  101250. },
  101251. enumerable: true,
  101252. configurable: true
  101253. });
  101254. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  101255. /**
  101256. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  101257. */
  101258. get: function () {
  101259. return this._vrDeviceOrientationCamera;
  101260. },
  101261. enumerable: true,
  101262. configurable: true
  101263. });
  101264. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  101265. get: function () {
  101266. var result = this._cameraGazer._teleportationRequestInitiated
  101267. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  101268. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  101269. return result;
  101270. },
  101271. enumerable: true,
  101272. configurable: true
  101273. });
  101274. // Raised when one of the controller has loaded successfully its associated default mesh
  101275. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  101276. if (this._leftController && this._leftController.webVRController == webVRController) {
  101277. if (webVRController.mesh) {
  101278. this._leftController._setLaserPointerParent(webVRController.mesh);
  101279. }
  101280. }
  101281. if (this._rightController && this._rightController.webVRController == webVRController) {
  101282. if (webVRController.mesh) {
  101283. this._rightController._setLaserPointerParent(webVRController.mesh);
  101284. }
  101285. }
  101286. try {
  101287. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  101288. }
  101289. catch (err) {
  101290. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  101291. }
  101292. };
  101293. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  101294. /**
  101295. * Gets a value indicating if we are currently in VR mode.
  101296. */
  101297. get: function () {
  101298. return this._webVRpresenting || this._fullscreenVRpresenting;
  101299. },
  101300. enumerable: true,
  101301. configurable: true
  101302. });
  101303. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  101304. var vrDisplay = this._scene.getEngine().getVRDevice();
  101305. if (vrDisplay) {
  101306. var wasPresenting = this._webVRpresenting;
  101307. this._webVRpresenting = vrDisplay.isPresenting;
  101308. if (wasPresenting && !this._webVRpresenting)
  101309. this.exitVR();
  101310. }
  101311. else {
  101312. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  101313. }
  101314. this.updateButtonVisibility();
  101315. };
  101316. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  101317. this._webVRsupported = eventArgs.vrSupported;
  101318. this._webVRready = !!eventArgs.vrDisplay;
  101319. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  101320. this.updateButtonVisibility();
  101321. };
  101322. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  101323. if (this._canvas && !this._useCustomVRButton) {
  101324. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  101325. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  101326. }
  101327. };
  101328. VRExperienceHelper.prototype.displayVRButton = function () {
  101329. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  101330. document.body.appendChild(this._btnVR);
  101331. this._btnVRDisplayed = true;
  101332. }
  101333. };
  101334. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  101335. if (!this._btnVR || this._useCustomVRButton) {
  101336. return;
  101337. }
  101338. this._btnVR.className = "babylonVRicon";
  101339. if (this.isInVRMode) {
  101340. this._btnVR.className += " vrdisplaypresenting";
  101341. }
  101342. else {
  101343. if (this._webVRready)
  101344. this._btnVR.className += " vrdisplayready";
  101345. if (this._webVRsupported)
  101346. this._btnVR.className += " vrdisplaysupported";
  101347. if (this._webVRrequesting)
  101348. this._btnVR.className += " vrdisplayrequesting";
  101349. }
  101350. };
  101351. /**
  101352. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  101353. * Otherwise, will use the fullscreen API.
  101354. */
  101355. VRExperienceHelper.prototype.enterVR = function () {
  101356. if (this.onEnteringVRObservable) {
  101357. try {
  101358. this.onEnteringVRObservable.notifyObservers(this);
  101359. }
  101360. catch (err) {
  101361. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  101362. }
  101363. }
  101364. if (this._scene.activeCamera) {
  101365. this._position = this._scene.activeCamera.position.clone();
  101366. // make sure that we return to the last active camera
  101367. this._existingCamera = this._scene.activeCamera;
  101368. }
  101369. if (this._webVRrequesting)
  101370. return;
  101371. // If WebVR is supported and a headset is connected
  101372. if (this._webVRready) {
  101373. if (!this._webVRpresenting) {
  101374. this._webVRCamera.position = this._position;
  101375. this._scene.activeCamera = this._webVRCamera;
  101376. }
  101377. }
  101378. else if (this._vrDeviceOrientationCamera) {
  101379. this._vrDeviceOrientationCamera.position = this._position;
  101380. if (this._scene.activeCamera) {
  101381. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101382. }
  101383. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  101384. this._scene.getEngine().switchFullscreen(true);
  101385. this.updateButtonVisibility();
  101386. }
  101387. if (this._scene.activeCamera && this._canvas) {
  101388. this._scene.activeCamera.attachControl(this._canvas);
  101389. }
  101390. if (this._interactionsEnabled) {
  101391. this._scene.registerBeforeRender(this.beforeRender);
  101392. }
  101393. this._hasEnteredVR = true;
  101394. };
  101395. /**
  101396. * Attempt to exit VR, or fullscreen.
  101397. */
  101398. VRExperienceHelper.prototype.exitVR = function () {
  101399. if (this._hasEnteredVR) {
  101400. if (this.onExitingVRObservable) {
  101401. try {
  101402. this.onExitingVRObservable.notifyObservers(this);
  101403. }
  101404. catch (err) {
  101405. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  101406. }
  101407. }
  101408. if (this._webVRpresenting) {
  101409. this._scene.getEngine().disableVR();
  101410. }
  101411. if (this._scene.activeCamera) {
  101412. this._position = this._scene.activeCamera.position.clone();
  101413. }
  101414. if (this._deviceOrientationCamera) {
  101415. this._deviceOrientationCamera.position = this._position;
  101416. this._scene.activeCamera = this._deviceOrientationCamera;
  101417. if (this._canvas) {
  101418. this._scene.activeCamera.attachControl(this._canvas);
  101419. }
  101420. }
  101421. else if (this._existingCamera) {
  101422. this._existingCamera.position = this._position;
  101423. this._scene.activeCamera = this._existingCamera;
  101424. }
  101425. this.updateButtonVisibility();
  101426. if (this._interactionsEnabled) {
  101427. this._scene.unregisterBeforeRender(this.beforeRender);
  101428. this._cameraGazer._gazeTracker.isVisible = false;
  101429. if (this._leftController) {
  101430. this._leftController._gazeTracker.isVisible = false;
  101431. }
  101432. if (this._rightController) {
  101433. this._rightController._gazeTracker.isVisible = false;
  101434. }
  101435. }
  101436. // resize to update width and height when exiting vr exits fullscreen
  101437. this._scene.getEngine().resize();
  101438. this._hasEnteredVR = false;
  101439. }
  101440. };
  101441. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  101442. /**
  101443. * The position of the vr experience helper.
  101444. */
  101445. get: function () {
  101446. return this._position;
  101447. },
  101448. /**
  101449. * Sets the position of the vr experience helper.
  101450. */
  101451. set: function (value) {
  101452. this._position = value;
  101453. if (this._scene.activeCamera) {
  101454. this._scene.activeCamera.position = value;
  101455. }
  101456. },
  101457. enumerable: true,
  101458. configurable: true
  101459. });
  101460. /**
  101461. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  101462. */
  101463. VRExperienceHelper.prototype.enableInteractions = function () {
  101464. var _this = this;
  101465. if (!this._interactionsEnabled) {
  101466. this._interactionsRequested = true;
  101467. if (this._leftController) {
  101468. this._enableInteractionOnController(this._leftController);
  101469. }
  101470. if (this._rightController) {
  101471. this._enableInteractionOnController(this._rightController);
  101472. }
  101473. this.raySelectionPredicate = function (mesh) {
  101474. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  101475. };
  101476. this.meshSelectionPredicate = function (mesh) {
  101477. return true;
  101478. };
  101479. this._raySelectionPredicate = function (mesh) {
  101480. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  101481. && mesh.name.indexOf("teleportationTarget") === -1
  101482. && mesh.name.indexOf("torusTeleportation") === -1)) {
  101483. return _this.raySelectionPredicate(mesh);
  101484. }
  101485. return false;
  101486. };
  101487. this._interactionsEnabled = true;
  101488. }
  101489. };
  101490. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  101491. get: function () {
  101492. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  101493. },
  101494. enumerable: true,
  101495. configurable: true
  101496. });
  101497. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  101498. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  101499. if (this._floorMeshesCollection[i].id === mesh.id) {
  101500. return true;
  101501. }
  101502. }
  101503. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  101504. return true;
  101505. }
  101506. return false;
  101507. };
  101508. /**
  101509. * Adds a floor mesh to be used for teleportation.
  101510. * @param floorMesh the mesh to be used for teleportation.
  101511. */
  101512. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  101513. if (!this._floorMeshesCollection) {
  101514. return;
  101515. }
  101516. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  101517. return;
  101518. }
  101519. this._floorMeshesCollection.push(floorMesh);
  101520. };
  101521. /**
  101522. * Removes a floor mesh from being used for teleportation.
  101523. * @param floorMesh the mesh to be removed.
  101524. */
  101525. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  101526. if (!this._floorMeshesCollection) {
  101527. return;
  101528. }
  101529. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  101530. if (meshIndex !== -1) {
  101531. this._floorMeshesCollection.splice(meshIndex, 1);
  101532. }
  101533. };
  101534. /**
  101535. * Enables interactions and teleportation using the VR controllers and gaze.
  101536. * @param vrTeleportationOptions options to modify teleportation behavior.
  101537. */
  101538. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  101539. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  101540. if (!this._teleportationInitialized) {
  101541. this._teleportationRequested = true;
  101542. this.enableInteractions();
  101543. if (vrTeleportationOptions.floorMeshName) {
  101544. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  101545. }
  101546. if (vrTeleportationOptions.floorMeshes) {
  101547. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  101548. }
  101549. if (this._leftController != null) {
  101550. this._enableTeleportationOnController(this._leftController);
  101551. }
  101552. if (this._rightController != null) {
  101553. this._enableTeleportationOnController(this._rightController);
  101554. }
  101555. // Creates an image processing post process for the vignette not relying
  101556. // on the main scene configuration for image processing to reduce setup and spaces
  101557. // (gamma/linear) conflicts.
  101558. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  101559. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  101560. imageProcessingConfiguration.vignetteEnabled = true;
  101561. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  101562. this._webVRCamera.detachPostProcess(this._postProcessMove);
  101563. this._teleportationInitialized = true;
  101564. if (this._isDefaultTeleportationTarget) {
  101565. this._createTeleportationCircles();
  101566. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  101567. }
  101568. }
  101569. };
  101570. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  101571. var _this = this;
  101572. var controllerMesh = controller.webVRController.mesh;
  101573. if (controllerMesh) {
  101574. controller._interactionsEnabled = true;
  101575. controller._activatePointer();
  101576. if (this.webVROptions.laserToggle) {
  101577. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  101578. // Enabling / disabling laserPointer
  101579. if (_this._displayLaserPointer && stateObject.value === 1) {
  101580. if (controller._activePointer) {
  101581. controller._deactivatePointer();
  101582. }
  101583. else {
  101584. controller._activatePointer();
  101585. }
  101586. if (_this.displayGaze) {
  101587. controller._gazeTracker.isVisible = controller._activePointer;
  101588. }
  101589. }
  101590. });
  101591. }
  101592. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  101593. var gazer = controller;
  101594. if (_this._noControllerIsActive) {
  101595. gazer = _this._cameraGazer;
  101596. }
  101597. if (!gazer._pointerDownOnMeshAsked) {
  101598. if (stateObject.value > _this._padSensibilityUp) {
  101599. gazer._selectionPointerDown();
  101600. }
  101601. }
  101602. else if (stateObject.value < _this._padSensibilityDown) {
  101603. gazer._selectionPointerUp();
  101604. }
  101605. });
  101606. }
  101607. };
  101608. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  101609. // Dont teleport if another gaze already requested teleportation
  101610. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  101611. return;
  101612. }
  101613. if (!gazer._teleportationRequestInitiated) {
  101614. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  101615. gazer._activatePointer();
  101616. gazer._teleportationRequestInitiated = true;
  101617. }
  101618. }
  101619. else {
  101620. // Listening to the proper controller values changes to confirm teleportation
  101621. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  101622. if (this._teleportActive) {
  101623. this.teleportCamera(this._haloCenter);
  101624. }
  101625. gazer._teleportationRequestInitiated = false;
  101626. }
  101627. }
  101628. };
  101629. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  101630. // Only rotate when user is not currently selecting a teleportation location
  101631. if (gazer._teleportationRequestInitiated) {
  101632. return;
  101633. }
  101634. if (!gazer._rotationLeftAsked) {
  101635. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  101636. gazer._rotationLeftAsked = true;
  101637. if (this._rotationAllowed) {
  101638. this._rotateCamera(false);
  101639. }
  101640. }
  101641. }
  101642. else {
  101643. if (stateObject.x > -this._padSensibilityDown) {
  101644. gazer._rotationLeftAsked = false;
  101645. }
  101646. }
  101647. if (!gazer._rotationRightAsked) {
  101648. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  101649. gazer._rotationRightAsked = true;
  101650. if (this._rotationAllowed) {
  101651. this._rotateCamera(true);
  101652. }
  101653. }
  101654. }
  101655. else {
  101656. if (stateObject.x < this._padSensibilityDown) {
  101657. gazer._rotationRightAsked = false;
  101658. }
  101659. }
  101660. };
  101661. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  101662. // Only teleport backwards when user is not currently selecting a teleportation location
  101663. if (gazer._teleportationRequestInitiated) {
  101664. return;
  101665. }
  101666. // Teleport backwards
  101667. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  101668. if (!gazer._teleportationBackRequestInitiated) {
  101669. if (!this.currentVRCamera) {
  101670. return;
  101671. }
  101672. // Get rotation and position of the current camera
  101673. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  101674. var position = this.currentVRCamera.position;
  101675. // If the camera has device position, use that instead
  101676. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  101677. rotation = this.currentVRCamera.deviceRotationQuaternion;
  101678. position = this.currentVRCamera.devicePosition;
  101679. }
  101680. // Get matrix with only the y rotation of the device rotation
  101681. rotation.toEulerAnglesToRef(this._workingVector);
  101682. this._workingVector.z = 0;
  101683. this._workingVector.x = 0;
  101684. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  101685. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  101686. // Rotate backwards ray by device rotation to cast at the ground behind the user
  101687. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  101688. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  101689. var ray = new BABYLON.Ray(position, this._workingVector);
  101690. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101691. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  101692. this.teleportCamera(hit.pickedPoint);
  101693. }
  101694. gazer._teleportationBackRequestInitiated = true;
  101695. }
  101696. }
  101697. else {
  101698. gazer._teleportationBackRequestInitiated = false;
  101699. }
  101700. };
  101701. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  101702. var _this = this;
  101703. var controllerMesh = controller.webVRController.mesh;
  101704. if (controllerMesh) {
  101705. if (!controller._interactionsEnabled) {
  101706. this._enableInteractionOnController(controller);
  101707. }
  101708. controller._interactionsEnabled = true;
  101709. controller._teleportationEnabled = true;
  101710. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101711. controller._dpadPressed = false;
  101712. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  101713. controller._dpadPressed = stateObject.pressed;
  101714. if (!controller._dpadPressed) {
  101715. controller._rotationLeftAsked = false;
  101716. controller._rotationRightAsked = false;
  101717. controller._teleportationBackRequestInitiated = false;
  101718. }
  101719. });
  101720. }
  101721. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  101722. if (_this.teleportationEnabled) {
  101723. _this._checkTeleportBackwards(stateObject, controller);
  101724. _this._checkTeleportWithRay(stateObject, controller);
  101725. }
  101726. _this._checkRotate(stateObject, controller);
  101727. });
  101728. }
  101729. };
  101730. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  101731. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  101732. this._teleportationTarget.isPickable = false;
  101733. var length = 512;
  101734. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  101735. dynamicTexture.hasAlpha = true;
  101736. var context = dynamicTexture.getContext();
  101737. var centerX = length / 2;
  101738. var centerY = length / 2;
  101739. var radius = 200;
  101740. context.beginPath();
  101741. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  101742. context.fillStyle = this._teleportationFillColor;
  101743. context.fill();
  101744. context.lineWidth = 10;
  101745. context.strokeStyle = this._teleportationBorderColor;
  101746. context.stroke();
  101747. context.closePath();
  101748. dynamicTexture.update();
  101749. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  101750. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  101751. this._teleportationTarget.material = teleportationCircleMaterial;
  101752. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  101753. torus.isPickable = false;
  101754. torus.parent = this._teleportationTarget;
  101755. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101756. var keys = [];
  101757. keys.push({
  101758. frame: 0,
  101759. value: 0
  101760. });
  101761. keys.push({
  101762. frame: 30,
  101763. value: 0.4
  101764. });
  101765. keys.push({
  101766. frame: 60,
  101767. value: 0
  101768. });
  101769. animationInnerCircle.setKeys(keys);
  101770. var easingFunction = new BABYLON.SineEase();
  101771. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101772. animationInnerCircle.setEasingFunction(easingFunction);
  101773. torus.animations = [];
  101774. torus.animations.push(animationInnerCircle);
  101775. this._scene.beginAnimation(torus, 0, 60, true);
  101776. this._hideTeleportationTarget();
  101777. };
  101778. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  101779. this._teleportActive = true;
  101780. if (this._teleportationInitialized) {
  101781. this._teleportationTarget.isVisible = true;
  101782. if (this._isDefaultTeleportationTarget) {
  101783. this._teleportationTarget.getChildren()[0].isVisible = true;
  101784. }
  101785. }
  101786. };
  101787. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  101788. this._teleportActive = false;
  101789. if (this._teleportationInitialized) {
  101790. this._teleportationTarget.isVisible = false;
  101791. if (this._isDefaultTeleportationTarget) {
  101792. this._teleportationTarget.getChildren()[0].isVisible = false;
  101793. }
  101794. }
  101795. };
  101796. VRExperienceHelper.prototype._rotateCamera = function (right) {
  101797. var _this = this;
  101798. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101799. return;
  101800. }
  101801. if (right) {
  101802. this._rotationAngle++;
  101803. }
  101804. else {
  101805. this._rotationAngle--;
  101806. }
  101807. this.currentVRCamera.animations = [];
  101808. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  101809. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101810. var animationRotationKeys = [];
  101811. animationRotationKeys.push({
  101812. frame: 0,
  101813. value: this.currentVRCamera.rotationQuaternion
  101814. });
  101815. animationRotationKeys.push({
  101816. frame: 6,
  101817. value: target
  101818. });
  101819. animationRotation.setKeys(animationRotationKeys);
  101820. animationRotation.setEasingFunction(this._circleEase);
  101821. this.currentVRCamera.animations.push(animationRotation);
  101822. this._postProcessMove.animations = [];
  101823. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101824. var vignetteWeightKeys = [];
  101825. vignetteWeightKeys.push({
  101826. frame: 0,
  101827. value: 0
  101828. });
  101829. vignetteWeightKeys.push({
  101830. frame: 3,
  101831. value: 4
  101832. });
  101833. vignetteWeightKeys.push({
  101834. frame: 6,
  101835. value: 0
  101836. });
  101837. animationPP.setKeys(vignetteWeightKeys);
  101838. animationPP.setEasingFunction(this._circleEase);
  101839. this._postProcessMove.animations.push(animationPP);
  101840. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101841. var vignetteStretchKeys = [];
  101842. vignetteStretchKeys.push({
  101843. frame: 0,
  101844. value: 0
  101845. });
  101846. vignetteStretchKeys.push({
  101847. frame: 3,
  101848. value: 10
  101849. });
  101850. vignetteStretchKeys.push({
  101851. frame: 6,
  101852. value: 0
  101853. });
  101854. animationPP2.setKeys(vignetteStretchKeys);
  101855. animationPP2.setEasingFunction(this._circleEase);
  101856. this._postProcessMove.animations.push(animationPP2);
  101857. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101858. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101859. this._postProcessMove.samples = 4;
  101860. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101861. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  101862. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101863. });
  101864. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  101865. };
  101866. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  101867. if (hit.pickedPoint) {
  101868. if (gazer._teleportationRequestInitiated) {
  101869. this._displayTeleportationTarget();
  101870. this._haloCenter.copyFrom(hit.pickedPoint);
  101871. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  101872. }
  101873. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  101874. if (pickNormal) {
  101875. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101876. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101877. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  101878. }
  101879. this._teleportationTarget.position.y += 0.1;
  101880. }
  101881. };
  101882. /**
  101883. * Teleports the users feet to the desired location
  101884. * @param location The location where the user's feet should be placed
  101885. */
  101886. VRExperienceHelper.prototype.teleportCamera = function (location) {
  101887. var _this = this;
  101888. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101889. return;
  101890. }
  101891. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  101892. // offset of the headset from the anchor.
  101893. if (this.webVRCamera.leftCamera) {
  101894. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  101895. this._workingVector.subtractInPlace(this.webVRCamera.position);
  101896. location.subtractToRef(this._workingVector, this._workingVector);
  101897. }
  101898. else {
  101899. this._workingVector.copyFrom(location);
  101900. }
  101901. // Add height to account for user's height offset
  101902. if (this.isInVRMode) {
  101903. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  101904. }
  101905. else {
  101906. this._workingVector.y += this._defaultHeight;
  101907. }
  101908. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  101909. // Create animation from the camera's position to the new location
  101910. this.currentVRCamera.animations = [];
  101911. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101912. var animationCameraTeleportationKeys = [{
  101913. frame: 0,
  101914. value: this.currentVRCamera.position
  101915. },
  101916. {
  101917. frame: 11,
  101918. value: this._workingVector
  101919. }
  101920. ];
  101921. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  101922. animationCameraTeleportation.setEasingFunction(this._circleEase);
  101923. this.currentVRCamera.animations.push(animationCameraTeleportation);
  101924. this._postProcessMove.animations = [];
  101925. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101926. var vignetteWeightKeys = [];
  101927. vignetteWeightKeys.push({
  101928. frame: 0,
  101929. value: 0
  101930. });
  101931. vignetteWeightKeys.push({
  101932. frame: 5,
  101933. value: 8
  101934. });
  101935. vignetteWeightKeys.push({
  101936. frame: 11,
  101937. value: 0
  101938. });
  101939. animationPP.setKeys(vignetteWeightKeys);
  101940. this._postProcessMove.animations.push(animationPP);
  101941. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101942. var vignetteStretchKeys = [];
  101943. vignetteStretchKeys.push({
  101944. frame: 0,
  101945. value: 0
  101946. });
  101947. vignetteStretchKeys.push({
  101948. frame: 5,
  101949. value: 10
  101950. });
  101951. vignetteStretchKeys.push({
  101952. frame: 11,
  101953. value: 0
  101954. });
  101955. animationPP2.setKeys(vignetteStretchKeys);
  101956. this._postProcessMove.animations.push(animationPP2);
  101957. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101958. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101959. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101960. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  101961. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101962. });
  101963. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  101964. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  101965. });
  101966. this._hideTeleportationTarget();
  101967. };
  101968. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  101969. if (normal) {
  101970. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  101971. if (angle < Math.PI / 2) {
  101972. normal.scaleInPlace(-1);
  101973. }
  101974. }
  101975. return normal;
  101976. };
  101977. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  101978. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101979. return;
  101980. }
  101981. var ray = gazer._getForwardRay(this._rayLength);
  101982. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101983. if (hit) {
  101984. // Populate the contrllers mesh that can be used for drag/drop
  101985. if (gazer._laserPointer) {
  101986. hit.originMesh = gazer._laserPointer.parent;
  101987. }
  101988. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  101989. }
  101990. gazer._currentHit = hit;
  101991. // Moving the gazeTracker on the mesh face targetted
  101992. if (hit && hit.pickedPoint) {
  101993. if (this._displayGaze) {
  101994. var multiplier = 1;
  101995. gazer._gazeTracker.isVisible = true;
  101996. if (gazer._isActionableMesh) {
  101997. multiplier = 3;
  101998. }
  101999. if (this.updateGazeTrackerScale) {
  102000. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  102001. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  102002. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  102003. }
  102004. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  102005. // To avoid z-fighting
  102006. var deltaFighting = 0.002;
  102007. if (pickNormal) {
  102008. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102009. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102010. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  102011. }
  102012. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  102013. if (gazer._gazeTracker.position.x < 0) {
  102014. gazer._gazeTracker.position.x += deltaFighting;
  102015. }
  102016. else {
  102017. gazer._gazeTracker.position.x -= deltaFighting;
  102018. }
  102019. if (gazer._gazeTracker.position.y < 0) {
  102020. gazer._gazeTracker.position.y += deltaFighting;
  102021. }
  102022. else {
  102023. gazer._gazeTracker.position.y -= deltaFighting;
  102024. }
  102025. if (gazer._gazeTracker.position.z < 0) {
  102026. gazer._gazeTracker.position.z += deltaFighting;
  102027. }
  102028. else {
  102029. gazer._gazeTracker.position.z -= deltaFighting;
  102030. }
  102031. }
  102032. // Changing the size of the laser pointer based on the distance from the targetted point
  102033. gazer._updatePointerDistance(hit.distance);
  102034. }
  102035. else {
  102036. gazer._updatePointerDistance();
  102037. gazer._gazeTracker.isVisible = false;
  102038. }
  102039. if (hit && hit.pickedMesh) {
  102040. // The object selected is the floor, we're in a teleportation scenario
  102041. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  102042. // Moving the teleportation area to this targetted point
  102043. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  102044. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  102045. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102046. }
  102047. gazer._currentMeshSelected = null;
  102048. if (gazer._teleportationRequestInitiated) {
  102049. this._moveTeleportationSelectorTo(hit, gazer, ray);
  102050. }
  102051. return;
  102052. }
  102053. // If not, we're in a selection scenario
  102054. //this._teleportationAllowed = false;
  102055. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  102056. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  102057. this.onNewMeshPicked.notifyObservers(hit);
  102058. gazer._currentMeshSelected = hit.pickedMesh;
  102059. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  102060. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  102061. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  102062. gazer._isActionableMesh = true;
  102063. }
  102064. else {
  102065. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102066. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102067. gazer._isActionableMesh = false;
  102068. }
  102069. try {
  102070. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  102071. }
  102072. catch (err) {
  102073. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  102074. }
  102075. }
  102076. else {
  102077. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102078. gazer._currentMeshSelected = null;
  102079. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102080. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102081. }
  102082. }
  102083. }
  102084. else {
  102085. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102086. gazer._currentMeshSelected = null;
  102087. //this._teleportationAllowed = false;
  102088. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102089. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102090. }
  102091. };
  102092. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  102093. if (mesh) {
  102094. this.onSelectedMeshUnselected.notifyObservers(mesh);
  102095. }
  102096. };
  102097. /**
  102098. * Sets the color of the laser ray from the vr controllers.
  102099. * @param color new color for the ray.
  102100. */
  102101. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  102102. if (this._leftController) {
  102103. this._leftController._setLaserPointerColor(color);
  102104. }
  102105. if (this._rightController) {
  102106. this._rightController._setLaserPointerColor(color);
  102107. }
  102108. };
  102109. /**
  102110. * Sets the color of the ray from the vr headsets gaze.
  102111. * @param color new color for the ray.
  102112. */
  102113. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  102114. if (!this._cameraGazer._gazeTracker.material) {
  102115. return;
  102116. }
  102117. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  102118. if (this._leftController) {
  102119. this._leftController._gazeTracker.material.emissiveColor = color;
  102120. }
  102121. if (this._rightController) {
  102122. this._rightController._gazeTracker.material.emissiveColor = color;
  102123. }
  102124. };
  102125. /**
  102126. * Exits VR and disposes of the vr experience helper
  102127. */
  102128. VRExperienceHelper.prototype.dispose = function () {
  102129. if (this.isInVRMode) {
  102130. this.exitVR();
  102131. }
  102132. if (this._postProcessMove) {
  102133. this._postProcessMove.dispose();
  102134. }
  102135. if (this._webVRCamera) {
  102136. this._webVRCamera.dispose();
  102137. }
  102138. if (this._vrDeviceOrientationCamera) {
  102139. this._vrDeviceOrientationCamera.dispose();
  102140. }
  102141. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  102142. document.body.removeChild(this._btnVR);
  102143. }
  102144. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  102145. this._deviceOrientationCamera.dispose();
  102146. }
  102147. if (this._cameraGazer) {
  102148. this._cameraGazer.dispose();
  102149. }
  102150. if (this._leftController) {
  102151. this._leftController.dispose();
  102152. }
  102153. if (this._rightController) {
  102154. this._rightController.dispose();
  102155. }
  102156. if (this._teleportationTarget) {
  102157. this._teleportationTarget.dispose();
  102158. }
  102159. this._floorMeshesCollection = [];
  102160. document.removeEventListener("keydown", this._onKeyDown);
  102161. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102162. window.removeEventListener("resize", this._onResize);
  102163. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  102164. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  102165. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  102166. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  102167. document.onmsfullscreenchange = null;
  102168. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  102169. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  102170. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  102171. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102172. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  102173. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  102174. this._scene.unregisterBeforeRender(this.beforeRender);
  102175. };
  102176. /**
  102177. * Gets the name of the VRExperienceHelper class
  102178. * @returns "VRExperienceHelper"
  102179. */
  102180. VRExperienceHelper.prototype.getClassName = function () {
  102181. return "VRExperienceHelper";
  102182. };
  102183. return VRExperienceHelper;
  102184. }());
  102185. BABYLON.VRExperienceHelper = VRExperienceHelper;
  102186. })(BABYLON || (BABYLON = {}));
  102187. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  102188. // Mainly based on these 2 articles :
  102189. // 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
  102190. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  102191. var BABYLON;
  102192. (function (BABYLON) {
  102193. /**
  102194. * Defines the potential axis of a Joystick
  102195. */
  102196. var JoystickAxis;
  102197. (function (JoystickAxis) {
  102198. /** X axis */
  102199. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  102200. /** Y axis */
  102201. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  102202. /** Z axis */
  102203. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  102204. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  102205. /**
  102206. * Class used to define virtual joystick (used in touch mode)
  102207. */
  102208. var VirtualJoystick = /** @class */ (function () {
  102209. /**
  102210. * Creates a new virtual joystick
  102211. * @param leftJoystick defines that the joystick is for left hand (false by default)
  102212. */
  102213. function VirtualJoystick(leftJoystick) {
  102214. var _this = this;
  102215. if (leftJoystick) {
  102216. this._leftJoystick = true;
  102217. }
  102218. else {
  102219. this._leftJoystick = false;
  102220. }
  102221. VirtualJoystick._globalJoystickIndex++;
  102222. // By default left & right arrow keys are moving the X
  102223. // and up & down keys are moving the Y
  102224. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102225. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102226. this.reverseLeftRight = false;
  102227. this.reverseUpDown = false;
  102228. // collections of pointers
  102229. this._touches = new BABYLON.StringDictionary();
  102230. this.deltaPosition = BABYLON.Vector3.Zero();
  102231. this._joystickSensibility = 25;
  102232. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102233. this._onResize = function (evt) {
  102234. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102235. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102236. if (VirtualJoystick.vjCanvas) {
  102237. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  102238. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  102239. }
  102240. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  102241. };
  102242. // injecting a canvas element on top of the canvas 3D game
  102243. if (!VirtualJoystick.vjCanvas) {
  102244. window.addEventListener("resize", this._onResize, false);
  102245. VirtualJoystick.vjCanvas = document.createElement("canvas");
  102246. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102247. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102248. VirtualJoystick.vjCanvas.width = window.innerWidth;
  102249. VirtualJoystick.vjCanvas.height = window.innerHeight;
  102250. VirtualJoystick.vjCanvas.style.width = "100%";
  102251. VirtualJoystick.vjCanvas.style.height = "100%";
  102252. VirtualJoystick.vjCanvas.style.position = "absolute";
  102253. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  102254. VirtualJoystick.vjCanvas.style.top = "0px";
  102255. VirtualJoystick.vjCanvas.style.left = "0px";
  102256. VirtualJoystick.vjCanvas.style.zIndex = "5";
  102257. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  102258. // Support for jQuery PEP polyfill
  102259. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  102260. var context = VirtualJoystick.vjCanvas.getContext('2d');
  102261. if (!context) {
  102262. throw new Error("Unable to create canvas for virtual joystick");
  102263. }
  102264. VirtualJoystick.vjCanvasContext = context;
  102265. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  102266. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102267. document.body.appendChild(VirtualJoystick.vjCanvas);
  102268. }
  102269. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  102270. this.pressed = false;
  102271. // default joystick color
  102272. this._joystickColor = "cyan";
  102273. this._joystickPointerID = -1;
  102274. // current joystick position
  102275. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  102276. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  102277. // origin joystick position
  102278. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  102279. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  102280. this._onPointerDownHandlerRef = function (evt) {
  102281. _this._onPointerDown(evt);
  102282. };
  102283. this._onPointerMoveHandlerRef = function (evt) {
  102284. _this._onPointerMove(evt);
  102285. };
  102286. this._onPointerUpHandlerRef = function (evt) {
  102287. _this._onPointerUp(evt);
  102288. };
  102289. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  102290. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  102291. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  102292. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  102293. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  102294. evt.preventDefault(); // Disables system menu
  102295. }, false);
  102296. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102297. }
  102298. /**
  102299. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  102300. * @param newJoystickSensibility defines the new sensibility
  102301. */
  102302. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  102303. this._joystickSensibility = newJoystickSensibility;
  102304. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102305. };
  102306. VirtualJoystick.prototype._onPointerDown = function (e) {
  102307. var positionOnScreenCondition;
  102308. e.preventDefault();
  102309. if (this._leftJoystick === true) {
  102310. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  102311. }
  102312. else {
  102313. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  102314. }
  102315. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  102316. // First contact will be dedicated to the virtual joystick
  102317. this._joystickPointerID = e.pointerId;
  102318. this._joystickPointerStartPos.x = e.clientX;
  102319. this._joystickPointerStartPos.y = e.clientY;
  102320. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  102321. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  102322. this._deltaJoystickVector.x = 0;
  102323. this._deltaJoystickVector.y = 0;
  102324. this.pressed = true;
  102325. this._touches.add(e.pointerId.toString(), e);
  102326. }
  102327. else {
  102328. // You can only trigger the action buttons with a joystick declared
  102329. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  102330. this._action();
  102331. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  102332. }
  102333. }
  102334. };
  102335. VirtualJoystick.prototype._onPointerMove = function (e) {
  102336. // If the current pointer is the one associated to the joystick (first touch contact)
  102337. if (this._joystickPointerID == e.pointerId) {
  102338. this._joystickPointerPos.x = e.clientX;
  102339. this._joystickPointerPos.y = e.clientY;
  102340. this._deltaJoystickVector = this._joystickPointerPos.clone();
  102341. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  102342. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  102343. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  102344. switch (this._axisTargetedByLeftAndRight) {
  102345. case JoystickAxis.X:
  102346. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  102347. break;
  102348. case JoystickAxis.Y:
  102349. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  102350. break;
  102351. case JoystickAxis.Z:
  102352. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  102353. break;
  102354. }
  102355. var directionUpDown = this.reverseUpDown ? 1 : -1;
  102356. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  102357. switch (this._axisTargetedByUpAndDown) {
  102358. case JoystickAxis.X:
  102359. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  102360. break;
  102361. case JoystickAxis.Y:
  102362. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  102363. break;
  102364. case JoystickAxis.Z:
  102365. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  102366. break;
  102367. }
  102368. }
  102369. else {
  102370. var data = this._touches.get(e.pointerId.toString());
  102371. if (data) {
  102372. data.x = e.clientX;
  102373. data.y = e.clientY;
  102374. }
  102375. }
  102376. };
  102377. VirtualJoystick.prototype._onPointerUp = function (e) {
  102378. if (this._joystickPointerID == e.pointerId) {
  102379. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  102380. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  102381. this._joystickPointerID = -1;
  102382. this.pressed = false;
  102383. }
  102384. else {
  102385. var touch = this._touches.get(e.pointerId.toString());
  102386. if (touch) {
  102387. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102388. }
  102389. }
  102390. this._deltaJoystickVector.x = 0;
  102391. this._deltaJoystickVector.y = 0;
  102392. this._touches.remove(e.pointerId.toString());
  102393. };
  102394. /**
  102395. * Change the color of the virtual joystick
  102396. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  102397. */
  102398. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  102399. this._joystickColor = newColor;
  102400. };
  102401. /**
  102402. * Defines a callback to call when the joystick is touched
  102403. * @param action defines the callback
  102404. */
  102405. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  102406. this._action = action;
  102407. };
  102408. /**
  102409. * Defines which axis you'd like to control for left & right
  102410. * @param axis defines the axis to use
  102411. */
  102412. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  102413. switch (axis) {
  102414. case JoystickAxis.X:
  102415. case JoystickAxis.Y:
  102416. case JoystickAxis.Z:
  102417. this._axisTargetedByLeftAndRight = axis;
  102418. break;
  102419. default:
  102420. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102421. break;
  102422. }
  102423. };
  102424. /**
  102425. * Defines which axis you'd like to control for up & down
  102426. * @param axis defines the axis to use
  102427. */
  102428. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  102429. switch (axis) {
  102430. case JoystickAxis.X:
  102431. case JoystickAxis.Y:
  102432. case JoystickAxis.Z:
  102433. this._axisTargetedByUpAndDown = axis;
  102434. break;
  102435. default:
  102436. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102437. break;
  102438. }
  102439. };
  102440. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  102441. var _this = this;
  102442. if (this.pressed) {
  102443. this._touches.forEach(function (key, touch) {
  102444. if (touch.pointerId === _this._joystickPointerID) {
  102445. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  102446. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  102447. VirtualJoystick.vjCanvasContext.beginPath();
  102448. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102449. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102450. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  102451. VirtualJoystick.vjCanvasContext.stroke();
  102452. VirtualJoystick.vjCanvasContext.closePath();
  102453. VirtualJoystick.vjCanvasContext.beginPath();
  102454. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102455. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102456. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  102457. VirtualJoystick.vjCanvasContext.stroke();
  102458. VirtualJoystick.vjCanvasContext.closePath();
  102459. VirtualJoystick.vjCanvasContext.beginPath();
  102460. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102461. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  102462. VirtualJoystick.vjCanvasContext.stroke();
  102463. VirtualJoystick.vjCanvasContext.closePath();
  102464. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  102465. }
  102466. else {
  102467. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102468. VirtualJoystick.vjCanvasContext.beginPath();
  102469. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  102470. VirtualJoystick.vjCanvasContext.beginPath();
  102471. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  102472. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102473. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  102474. VirtualJoystick.vjCanvasContext.stroke();
  102475. VirtualJoystick.vjCanvasContext.closePath();
  102476. touch.prevX = touch.x;
  102477. touch.prevY = touch.y;
  102478. }
  102479. ;
  102480. });
  102481. }
  102482. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102483. };
  102484. /**
  102485. * Release internal HTML canvas
  102486. */
  102487. VirtualJoystick.prototype.releaseCanvas = function () {
  102488. if (VirtualJoystick.vjCanvas) {
  102489. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  102490. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  102491. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  102492. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  102493. window.removeEventListener("resize", this._onResize);
  102494. document.body.removeChild(VirtualJoystick.vjCanvas);
  102495. VirtualJoystick.vjCanvas = null;
  102496. }
  102497. };
  102498. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  102499. VirtualJoystick._globalJoystickIndex = 0;
  102500. return VirtualJoystick;
  102501. }());
  102502. BABYLON.VirtualJoystick = VirtualJoystick;
  102503. })(BABYLON || (BABYLON = {}));
  102504. //# sourceMappingURL=babylon.virtualJoystick.js.map
  102505. var BABYLON;
  102506. (function (BABYLON) {
  102507. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  102508. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  102509. });
  102510. /**
  102511. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  102512. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102513. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102514. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102515. */
  102516. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  102517. __extends(VirtualJoysticksCamera, _super);
  102518. /**
  102519. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  102520. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102521. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102522. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102523. * @param name Define the name of the camera in the scene
  102524. * @param position Define the start position of the camera in the scene
  102525. * @param scene Define the scene the camera belongs to
  102526. */
  102527. function VirtualJoysticksCamera(name, position, scene) {
  102528. var _this = _super.call(this, name, position, scene) || this;
  102529. _this.inputs.addVirtualJoystick();
  102530. return _this;
  102531. }
  102532. /**
  102533. * Gets the current object class name.
  102534. * @return the class name
  102535. */
  102536. VirtualJoysticksCamera.prototype.getClassName = function () {
  102537. return "VirtualJoysticksCamera";
  102538. };
  102539. return VirtualJoysticksCamera;
  102540. }(BABYLON.FreeCamera));
  102541. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  102542. })(BABYLON || (BABYLON = {}));
  102543. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  102544. var BABYLON;
  102545. (function (BABYLON) {
  102546. /**
  102547. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  102548. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  102549. */
  102550. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  102551. function FreeCameraVirtualJoystickInput() {
  102552. }
  102553. /**
  102554. * Gets the left stick of the virtual joystick.
  102555. * @returns The virtual Joystick
  102556. */
  102557. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  102558. return this._leftjoystick;
  102559. };
  102560. /**
  102561. * Gets the right stick of the virtual joystick.
  102562. * @returns The virtual Joystick
  102563. */
  102564. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  102565. return this._rightjoystick;
  102566. };
  102567. /**
  102568. * Update the current camera state depending on the inputs that have been used this frame.
  102569. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  102570. */
  102571. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  102572. if (this._leftjoystick) {
  102573. var camera = this.camera;
  102574. var speed = camera._computeLocalCameraSpeed() * 50;
  102575. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  102576. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  102577. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  102578. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  102579. if (!this._leftjoystick.pressed) {
  102580. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  102581. }
  102582. if (!this._rightjoystick.pressed) {
  102583. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  102584. }
  102585. }
  102586. };
  102587. /**
  102588. * Attach the input controls to a specific dom element to get the input from.
  102589. * @param element Defines the element the controls should be listened from
  102590. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  102591. */
  102592. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  102593. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  102594. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  102595. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  102596. this._leftjoystick.setJoystickSensibility(0.15);
  102597. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  102598. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  102599. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  102600. this._rightjoystick.reverseUpDown = true;
  102601. this._rightjoystick.setJoystickSensibility(0.05);
  102602. this._rightjoystick.setJoystickColor("yellow");
  102603. };
  102604. /**
  102605. * Detach the current controls from the specified dom element.
  102606. * @param element Defines the element to stop listening the inputs from
  102607. */
  102608. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  102609. this._leftjoystick.releaseCanvas();
  102610. this._rightjoystick.releaseCanvas();
  102611. };
  102612. /**
  102613. * Gets the class name of the current intput.
  102614. * @returns the class name
  102615. */
  102616. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  102617. return "FreeCameraVirtualJoystickInput";
  102618. };
  102619. /**
  102620. * Get the friendly name associated with the input class.
  102621. * @returns the input friendly name
  102622. */
  102623. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  102624. return "virtualJoystick";
  102625. };
  102626. return FreeCameraVirtualJoystickInput;
  102627. }());
  102628. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  102629. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  102630. })(BABYLON || (BABYLON = {}));
  102631. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  102632. var BABYLON;
  102633. (function (BABYLON) {
  102634. var SimplificationSettings = /** @class */ (function () {
  102635. function SimplificationSettings(quality, distance, optimizeMesh) {
  102636. this.quality = quality;
  102637. this.distance = distance;
  102638. this.optimizeMesh = optimizeMesh;
  102639. }
  102640. return SimplificationSettings;
  102641. }());
  102642. BABYLON.SimplificationSettings = SimplificationSettings;
  102643. var SimplificationQueue = /** @class */ (function () {
  102644. function SimplificationQueue() {
  102645. this.running = false;
  102646. this._simplificationArray = [];
  102647. }
  102648. SimplificationQueue.prototype.addTask = function (task) {
  102649. this._simplificationArray.push(task);
  102650. };
  102651. SimplificationQueue.prototype.executeNext = function () {
  102652. var task = this._simplificationArray.pop();
  102653. if (task) {
  102654. this.running = true;
  102655. this.runSimplification(task);
  102656. }
  102657. else {
  102658. this.running = false;
  102659. }
  102660. };
  102661. SimplificationQueue.prototype.runSimplification = function (task) {
  102662. var _this = this;
  102663. if (task.parallelProcessing) {
  102664. //parallel simplifier
  102665. task.settings.forEach(function (setting) {
  102666. var simplifier = _this.getSimplifier(task);
  102667. simplifier.simplify(setting, function (newMesh) {
  102668. task.mesh.addLODLevel(setting.distance, newMesh);
  102669. newMesh.isVisible = true;
  102670. //check if it is the last
  102671. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  102672. //all done, run the success callback.
  102673. task.successCallback();
  102674. }
  102675. _this.executeNext();
  102676. });
  102677. });
  102678. }
  102679. else {
  102680. //single simplifier.
  102681. var simplifier = this.getSimplifier(task);
  102682. var runDecimation = function (setting, callback) {
  102683. simplifier.simplify(setting, function (newMesh) {
  102684. task.mesh.addLODLevel(setting.distance, newMesh);
  102685. newMesh.isVisible = true;
  102686. //run the next quality level
  102687. callback();
  102688. });
  102689. };
  102690. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  102691. runDecimation(task.settings[loop.index], function () {
  102692. loop.executeNext();
  102693. });
  102694. }, function () {
  102695. //execution ended, run the success callback.
  102696. if (task.successCallback) {
  102697. task.successCallback();
  102698. }
  102699. _this.executeNext();
  102700. });
  102701. }
  102702. };
  102703. SimplificationQueue.prototype.getSimplifier = function (task) {
  102704. switch (task.simplificationType) {
  102705. case SimplificationType.QUADRATIC:
  102706. default:
  102707. return new QuadraticErrorSimplification(task.mesh);
  102708. }
  102709. };
  102710. return SimplificationQueue;
  102711. }());
  102712. BABYLON.SimplificationQueue = SimplificationQueue;
  102713. /**
  102714. * The implemented types of simplification
  102715. * At the moment only Quadratic Error Decimation is implemented
  102716. */
  102717. var SimplificationType;
  102718. (function (SimplificationType) {
  102719. /** Quadratic error decimation */
  102720. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  102721. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  102722. var DecimationTriangle = /** @class */ (function () {
  102723. function DecimationTriangle(vertices) {
  102724. this.vertices = vertices;
  102725. this.error = new Array(4);
  102726. this.deleted = false;
  102727. this.isDirty = false;
  102728. this.deletePending = false;
  102729. this.borderFactor = 0;
  102730. }
  102731. return DecimationTriangle;
  102732. }());
  102733. BABYLON.DecimationTriangle = DecimationTriangle;
  102734. var DecimationVertex = /** @class */ (function () {
  102735. function DecimationVertex(position, id) {
  102736. this.position = position;
  102737. this.id = id;
  102738. this.isBorder = true;
  102739. this.q = new QuadraticMatrix();
  102740. this.triangleCount = 0;
  102741. this.triangleStart = 0;
  102742. this.originalOffsets = [];
  102743. }
  102744. DecimationVertex.prototype.updatePosition = function (newPosition) {
  102745. this.position.copyFrom(newPosition);
  102746. };
  102747. return DecimationVertex;
  102748. }());
  102749. BABYLON.DecimationVertex = DecimationVertex;
  102750. var QuadraticMatrix = /** @class */ (function () {
  102751. function QuadraticMatrix(data) {
  102752. this.data = new Array(10);
  102753. for (var i = 0; i < 10; ++i) {
  102754. if (data && data[i]) {
  102755. this.data[i] = data[i];
  102756. }
  102757. else {
  102758. this.data[i] = 0;
  102759. }
  102760. }
  102761. }
  102762. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  102763. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  102764. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  102765. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  102766. return det;
  102767. };
  102768. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  102769. for (var i = 0; i < 10; ++i) {
  102770. this.data[i] += matrix.data[i];
  102771. }
  102772. };
  102773. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  102774. for (var i = 0; i < 10; ++i) {
  102775. this.data[i] += data[i];
  102776. }
  102777. };
  102778. QuadraticMatrix.prototype.add = function (matrix) {
  102779. var m = new QuadraticMatrix();
  102780. for (var i = 0; i < 10; ++i) {
  102781. m.data[i] = this.data[i] + matrix.data[i];
  102782. }
  102783. return m;
  102784. };
  102785. QuadraticMatrix.FromData = function (a, b, c, d) {
  102786. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  102787. };
  102788. //returning an array to avoid garbage collection
  102789. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  102790. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  102791. };
  102792. return QuadraticMatrix;
  102793. }());
  102794. BABYLON.QuadraticMatrix = QuadraticMatrix;
  102795. var Reference = /** @class */ (function () {
  102796. function Reference(vertexId, triangleId) {
  102797. this.vertexId = vertexId;
  102798. this.triangleId = triangleId;
  102799. }
  102800. return Reference;
  102801. }());
  102802. BABYLON.Reference = Reference;
  102803. /**
  102804. * An implementation of the Quadratic Error simplification algorithm.
  102805. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  102806. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  102807. * @author RaananW
  102808. */
  102809. var QuadraticErrorSimplification = /** @class */ (function () {
  102810. function QuadraticErrorSimplification(_mesh) {
  102811. this._mesh = _mesh;
  102812. this.syncIterations = 5000;
  102813. this.aggressiveness = 7;
  102814. this.decimationIterations = 100;
  102815. this.boundingBoxEpsilon = BABYLON.Epsilon;
  102816. }
  102817. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  102818. var _this = this;
  102819. this.initDecimatedMesh();
  102820. //iterating through the submeshes array, one after the other.
  102821. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  102822. _this.initWithMesh(loop.index, function () {
  102823. _this.runDecimation(settings, loop.index, function () {
  102824. loop.executeNext();
  102825. });
  102826. }, settings.optimizeMesh);
  102827. }, function () {
  102828. setTimeout(function () {
  102829. successCallback(_this._reconstructedMesh);
  102830. }, 0);
  102831. });
  102832. };
  102833. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  102834. var _this = this;
  102835. var targetCount = ~~(this.triangles.length * settings.quality);
  102836. var deletedTriangles = 0;
  102837. var triangleCount = this.triangles.length;
  102838. var iterationFunction = function (iteration, callback) {
  102839. setTimeout(function () {
  102840. if (iteration % 5 === 0) {
  102841. _this.updateMesh(iteration === 0);
  102842. }
  102843. for (var i = 0; i < _this.triangles.length; ++i) {
  102844. _this.triangles[i].isDirty = false;
  102845. }
  102846. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  102847. var trianglesIterator = function (i) {
  102848. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  102849. var t = _this.triangles[tIdx];
  102850. if (!t)
  102851. return;
  102852. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  102853. return;
  102854. }
  102855. for (var j = 0; j < 3; ++j) {
  102856. if (t.error[j] < threshold) {
  102857. var deleted0 = [];
  102858. var deleted1 = [];
  102859. var v0 = t.vertices[j];
  102860. var v1 = t.vertices[(j + 1) % 3];
  102861. if (v0.isBorder || v1.isBorder)
  102862. continue;
  102863. var p = BABYLON.Vector3.Zero();
  102864. var n = BABYLON.Vector3.Zero();
  102865. var uv = BABYLON.Vector2.Zero();
  102866. var color = new BABYLON.Color4(0, 0, 0, 1);
  102867. _this.calculateError(v0, v1, p, n, uv, color);
  102868. var delTr = new Array();
  102869. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  102870. continue;
  102871. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  102872. continue;
  102873. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  102874. continue;
  102875. var uniqueArray = new Array();
  102876. delTr.forEach(function (deletedT) {
  102877. if (uniqueArray.indexOf(deletedT) === -1) {
  102878. deletedT.deletePending = true;
  102879. uniqueArray.push(deletedT);
  102880. }
  102881. });
  102882. if (uniqueArray.length % 2 !== 0) {
  102883. continue;
  102884. }
  102885. v0.q = v1.q.add(v0.q);
  102886. v0.updatePosition(p);
  102887. var tStart = _this.references.length;
  102888. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  102889. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  102890. var tCount = _this.references.length - tStart;
  102891. if (tCount <= v0.triangleCount) {
  102892. if (tCount) {
  102893. for (var c = 0; c < tCount; c++) {
  102894. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  102895. }
  102896. }
  102897. }
  102898. else {
  102899. v0.triangleStart = tStart;
  102900. }
  102901. v0.triangleCount = tCount;
  102902. break;
  102903. }
  102904. }
  102905. };
  102906. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  102907. }, 0);
  102908. };
  102909. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  102910. if (triangleCount - deletedTriangles <= targetCount)
  102911. loop.breakLoop();
  102912. else {
  102913. iterationFunction(loop.index, function () {
  102914. loop.executeNext();
  102915. });
  102916. }
  102917. }, function () {
  102918. setTimeout(function () {
  102919. //reconstruct this part of the mesh
  102920. _this.reconstructMesh(submeshIndex);
  102921. successCallback();
  102922. }, 0);
  102923. });
  102924. };
  102925. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  102926. var _this = this;
  102927. this.vertices = [];
  102928. this.triangles = [];
  102929. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102930. var indices = this._mesh.getIndices();
  102931. var submesh = this._mesh.subMeshes[submeshIndex];
  102932. var findInVertices = function (positionToSearch) {
  102933. if (optimizeMesh) {
  102934. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  102935. if (_this.vertices[ii].position.equals(positionToSearch)) {
  102936. return _this.vertices[ii];
  102937. }
  102938. }
  102939. }
  102940. return null;
  102941. };
  102942. var vertexReferences = [];
  102943. var vertexInit = function (i) {
  102944. if (!positionData) {
  102945. return;
  102946. }
  102947. var offset = i + submesh.verticesStart;
  102948. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  102949. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  102950. vertex.originalOffsets.push(offset);
  102951. if (vertex.id === _this.vertices.length) {
  102952. _this.vertices.push(vertex);
  102953. }
  102954. vertexReferences.push(vertex.id);
  102955. };
  102956. //var totalVertices = mesh.getTotalVertices();
  102957. var totalVertices = submesh.verticesCount;
  102958. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  102959. var indicesInit = function (i) {
  102960. if (!indices) {
  102961. return;
  102962. }
  102963. var offset = (submesh.indexStart / 3) + i;
  102964. var pos = (offset * 3);
  102965. var i0 = indices[pos + 0];
  102966. var i1 = indices[pos + 1];
  102967. var i2 = indices[pos + 2];
  102968. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  102969. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  102970. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  102971. var triangle = new DecimationTriangle([v0, v1, v2]);
  102972. triangle.originalOffset = pos;
  102973. _this.triangles.push(triangle);
  102974. };
  102975. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  102976. _this.init(callback);
  102977. });
  102978. });
  102979. };
  102980. QuadraticErrorSimplification.prototype.init = function (callback) {
  102981. var _this = this;
  102982. var triangleInit1 = function (i) {
  102983. var t = _this.triangles[i];
  102984. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  102985. for (var j = 0; j < 3; j++) {
  102986. 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))));
  102987. }
  102988. };
  102989. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  102990. var triangleInit2 = function (i) {
  102991. var t = _this.triangles[i];
  102992. for (var j = 0; j < 3; ++j) {
  102993. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  102994. }
  102995. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102996. };
  102997. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  102998. callback();
  102999. });
  103000. });
  103001. };
  103002. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  103003. var newTriangles = [];
  103004. var i;
  103005. for (i = 0; i < this.vertices.length; ++i) {
  103006. this.vertices[i].triangleCount = 0;
  103007. }
  103008. var t;
  103009. var j;
  103010. for (i = 0; i < this.triangles.length; ++i) {
  103011. if (!this.triangles[i].deleted) {
  103012. t = this.triangles[i];
  103013. for (j = 0; j < 3; ++j) {
  103014. t.vertices[j].triangleCount = 1;
  103015. }
  103016. newTriangles.push(t);
  103017. }
  103018. }
  103019. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  103020. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  103021. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  103022. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  103023. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  103024. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  103025. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  103026. var vertexCount = 0;
  103027. for (i = 0; i < this.vertices.length; ++i) {
  103028. var vertex = this.vertices[i];
  103029. vertex.id = vertexCount;
  103030. if (vertex.triangleCount) {
  103031. vertex.originalOffsets.forEach(function (originalOffset) {
  103032. if (!normalData) {
  103033. return;
  103034. }
  103035. newPositionData.push(vertex.position.x);
  103036. newPositionData.push(vertex.position.y);
  103037. newPositionData.push(vertex.position.z);
  103038. newNormalData.push(normalData[originalOffset * 3]);
  103039. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  103040. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  103041. if (uvs && uvs.length) {
  103042. newUVsData.push(uvs[(originalOffset * 2)]);
  103043. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  103044. }
  103045. else if (colorsData && colorsData.length) {
  103046. newColorsData.push(colorsData[(originalOffset * 4)]);
  103047. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  103048. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  103049. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  103050. }
  103051. ++vertexCount;
  103052. });
  103053. }
  103054. }
  103055. var startingIndex = this._reconstructedMesh.getTotalIndices();
  103056. var startingVertex = this._reconstructedMesh.getTotalVertices();
  103057. var submeshesArray = this._reconstructedMesh.subMeshes;
  103058. this._reconstructedMesh.subMeshes = [];
  103059. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  103060. var originalIndices = this._mesh.getIndices();
  103061. for (i = 0; i < newTriangles.length; ++i) {
  103062. t = newTriangles[i]; //now get the new referencing point for each vertex
  103063. [0, 1, 2].forEach(function (idx) {
  103064. var id = originalIndices[t.originalOffset + idx];
  103065. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  103066. if (offset < 0)
  103067. offset = 0;
  103068. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  103069. });
  103070. }
  103071. //overwriting the old vertex buffers and indices.
  103072. this._reconstructedMesh.setIndices(newIndicesArray);
  103073. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  103074. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  103075. if (newUVsData.length > 0)
  103076. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  103077. if (newColorsData.length > 0)
  103078. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  103079. //create submesh
  103080. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  103081. if (submeshIndex > 0) {
  103082. this._reconstructedMesh.subMeshes = [];
  103083. submeshesArray.forEach(function (submesh) {
  103084. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  103085. });
  103086. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  103087. }
  103088. };
  103089. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  103090. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  103091. this._reconstructedMesh.material = this._mesh.material;
  103092. this._reconstructedMesh.parent = this._mesh.parent;
  103093. this._reconstructedMesh.isVisible = false;
  103094. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  103095. };
  103096. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  103097. for (var i = 0; i < vertex1.triangleCount; ++i) {
  103098. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  103099. if (t.deleted)
  103100. continue;
  103101. var s = this.references[vertex1.triangleStart + i].vertexId;
  103102. var v1 = t.vertices[(s + 1) % 3];
  103103. var v2 = t.vertices[(s + 2) % 3];
  103104. if ((v1 === vertex2 || v2 === vertex2)) {
  103105. deletedArray[i] = true;
  103106. delTr.push(t);
  103107. continue;
  103108. }
  103109. var d1 = v1.position.subtract(point);
  103110. d1 = d1.normalize();
  103111. var d2 = v2.position.subtract(point);
  103112. d2 = d2.normalize();
  103113. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  103114. return true;
  103115. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  103116. deletedArray[i] = false;
  103117. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  103118. return true;
  103119. }
  103120. return false;
  103121. };
  103122. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  103123. var newDeleted = deletedTriangles;
  103124. for (var i = 0; i < vertex.triangleCount; ++i) {
  103125. var ref = this.references[vertex.triangleStart + i];
  103126. var t = this.triangles[ref.triangleId];
  103127. if (t.deleted)
  103128. continue;
  103129. if (deletedArray[i] && t.deletePending) {
  103130. t.deleted = true;
  103131. newDeleted++;
  103132. continue;
  103133. }
  103134. t.vertices[ref.vertexId] = origVertex;
  103135. t.isDirty = true;
  103136. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  103137. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  103138. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  103139. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103140. this.references.push(ref);
  103141. }
  103142. return newDeleted;
  103143. };
  103144. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  103145. for (var i = 0; i < this.vertices.length; ++i) {
  103146. var vCount = [];
  103147. var vId = [];
  103148. var v = this.vertices[i];
  103149. var j;
  103150. for (j = 0; j < v.triangleCount; ++j) {
  103151. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  103152. for (var ii = 0; ii < 3; ii++) {
  103153. var ofs = 0;
  103154. var vv = triangle.vertices[ii];
  103155. while (ofs < vCount.length) {
  103156. if (vId[ofs] === vv.id)
  103157. break;
  103158. ++ofs;
  103159. }
  103160. if (ofs === vCount.length) {
  103161. vCount.push(1);
  103162. vId.push(vv.id);
  103163. }
  103164. else {
  103165. vCount[ofs]++;
  103166. }
  103167. }
  103168. }
  103169. for (j = 0; j < vCount.length; ++j) {
  103170. if (vCount[j] === 1) {
  103171. this.vertices[vId[j]].isBorder = true;
  103172. }
  103173. else {
  103174. this.vertices[vId[j]].isBorder = false;
  103175. }
  103176. }
  103177. }
  103178. };
  103179. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  103180. if (identifyBorders === void 0) { identifyBorders = false; }
  103181. var i;
  103182. if (!identifyBorders) {
  103183. var newTrianglesVector = [];
  103184. for (i = 0; i < this.triangles.length; ++i) {
  103185. if (!this.triangles[i].deleted) {
  103186. newTrianglesVector.push(this.triangles[i]);
  103187. }
  103188. }
  103189. this.triangles = newTrianglesVector;
  103190. }
  103191. for (i = 0; i < this.vertices.length; ++i) {
  103192. this.vertices[i].triangleCount = 0;
  103193. this.vertices[i].triangleStart = 0;
  103194. }
  103195. var t;
  103196. var j;
  103197. var v;
  103198. for (i = 0; i < this.triangles.length; ++i) {
  103199. t = this.triangles[i];
  103200. for (j = 0; j < 3; ++j) {
  103201. v = t.vertices[j];
  103202. v.triangleCount++;
  103203. }
  103204. }
  103205. var tStart = 0;
  103206. for (i = 0; i < this.vertices.length; ++i) {
  103207. this.vertices[i].triangleStart = tStart;
  103208. tStart += this.vertices[i].triangleCount;
  103209. this.vertices[i].triangleCount = 0;
  103210. }
  103211. var newReferences = new Array(this.triangles.length * 3);
  103212. for (i = 0; i < this.triangles.length; ++i) {
  103213. t = this.triangles[i];
  103214. for (j = 0; j < 3; ++j) {
  103215. v = t.vertices[j];
  103216. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  103217. v.triangleCount++;
  103218. }
  103219. }
  103220. this.references = newReferences;
  103221. if (identifyBorders) {
  103222. this.identifyBorder();
  103223. }
  103224. };
  103225. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  103226. var x = point.x;
  103227. var y = point.y;
  103228. var z = point.z;
  103229. 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
  103230. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  103231. };
  103232. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  103233. var q = vertex1.q.add(vertex2.q);
  103234. var border = vertex1.isBorder && vertex2.isBorder;
  103235. var error = 0;
  103236. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  103237. if (qDet !== 0 && !border) {
  103238. if (!pointResult) {
  103239. pointResult = BABYLON.Vector3.Zero();
  103240. }
  103241. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  103242. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  103243. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  103244. error = this.vertexError(q, pointResult);
  103245. }
  103246. else {
  103247. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  103248. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  103249. var error1 = this.vertexError(q, vertex1.position);
  103250. var error2 = this.vertexError(q, vertex2.position);
  103251. var error3 = this.vertexError(q, p3);
  103252. error = Math.min(error1, error2, error3);
  103253. if (error === error1) {
  103254. if (pointResult) {
  103255. pointResult.copyFrom(vertex1.position);
  103256. }
  103257. }
  103258. else if (error === error2) {
  103259. if (pointResult) {
  103260. pointResult.copyFrom(vertex2.position);
  103261. }
  103262. }
  103263. else {
  103264. if (pointResult) {
  103265. pointResult.copyFrom(p3);
  103266. }
  103267. }
  103268. }
  103269. return error;
  103270. };
  103271. return QuadraticErrorSimplification;
  103272. }());
  103273. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  103274. })(BABYLON || (BABYLON = {}));
  103275. //# sourceMappingURL=babylon.meshSimplification.js.map
  103276. var BABYLON;
  103277. (function (BABYLON) {
  103278. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  103279. get: function () {
  103280. if (!this._simplificationQueue) {
  103281. this._simplificationQueue = new BABYLON.SimplificationQueue();
  103282. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  103283. if (!component) {
  103284. component = new SimplicationQueueSceneComponent(this);
  103285. this._addComponent(component);
  103286. }
  103287. }
  103288. return this._simplificationQueue;
  103289. },
  103290. set: function (value) {
  103291. this._simplificationQueue = value;
  103292. },
  103293. enumerable: true,
  103294. configurable: true
  103295. });
  103296. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  103297. if (parallelProcessing === void 0) { parallelProcessing = true; }
  103298. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  103299. this.getScene().simplificationQueue.addTask({
  103300. settings: settings,
  103301. parallelProcessing: parallelProcessing,
  103302. mesh: this,
  103303. simplificationType: simplificationType,
  103304. successCallback: successCallback
  103305. });
  103306. return this;
  103307. };
  103308. /**
  103309. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  103310. * created in a scene
  103311. */
  103312. var SimplicationQueueSceneComponent = /** @class */ (function () {
  103313. /**
  103314. * Creates a new instance of the component for the given scene
  103315. * @param scene Defines the scene to register the component in
  103316. */
  103317. function SimplicationQueueSceneComponent(scene) {
  103318. /**
  103319. * The component name helpfull to identify the component in the list of scene components.
  103320. */
  103321. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  103322. this.scene = scene;
  103323. }
  103324. /**
  103325. * Registers the component in a given scene
  103326. */
  103327. SimplicationQueueSceneComponent.prototype.register = function () {
  103328. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  103329. };
  103330. /**
  103331. * Rebuilds the elements related to this component in case of
  103332. * context lost for instance.
  103333. */
  103334. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  103335. // Nothing to do for this component
  103336. };
  103337. /**
  103338. * Disposes the component and the associated ressources
  103339. */
  103340. SimplicationQueueSceneComponent.prototype.dispose = function () {
  103341. // Nothing to do for this component
  103342. };
  103343. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  103344. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  103345. this.scene._simplificationQueue.executeNext();
  103346. }
  103347. };
  103348. return SimplicationQueueSceneComponent;
  103349. }());
  103350. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  103351. })(BABYLON || (BABYLON = {}));
  103352. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  103353. var BABYLON;
  103354. (function (BABYLON) {
  103355. /**
  103356. * Class used to represent a specific level of detail of a mesh
  103357. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  103358. */
  103359. var MeshLODLevel = /** @class */ (function () {
  103360. /**
  103361. * Creates a new LOD level
  103362. * @param distance defines the distance where this level should star being displayed
  103363. * @param mesh defines the mesh to use to render this level
  103364. */
  103365. function MeshLODLevel(
  103366. /** Defines the distance where this level should star being displayed */
  103367. distance,
  103368. /** Defines the mesh to use to render this level */
  103369. mesh) {
  103370. this.distance = distance;
  103371. this.mesh = mesh;
  103372. }
  103373. return MeshLODLevel;
  103374. }());
  103375. BABYLON.MeshLODLevel = MeshLODLevel;
  103376. })(BABYLON || (BABYLON = {}));
  103377. //# sourceMappingURL=babylon.meshLODLevel.js.map
  103378. var BABYLON;
  103379. (function (BABYLON) {
  103380. /**
  103381. * Defines the root class used to create scene optimization to use with SceneOptimizer
  103382. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103383. */
  103384. var SceneOptimization = /** @class */ (function () {
  103385. /**
  103386. * Creates the SceneOptimization object
  103387. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103388. * @param desc defines the description associated with the optimization
  103389. */
  103390. function SceneOptimization(
  103391. /**
  103392. * Defines the priority of this optimization (0 by default which means first in the list)
  103393. */
  103394. priority) {
  103395. if (priority === void 0) { priority = 0; }
  103396. this.priority = priority;
  103397. }
  103398. /**
  103399. * Gets a string describing the action executed by the current optimization
  103400. * @returns description string
  103401. */
  103402. SceneOptimization.prototype.getDescription = function () {
  103403. return "";
  103404. };
  103405. /**
  103406. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103407. * @param scene defines the current scene where to apply this optimization
  103408. * @param optimizer defines the current optimizer
  103409. * @returns true if everything that can be done was applied
  103410. */
  103411. SceneOptimization.prototype.apply = function (scene, optimizer) {
  103412. return true;
  103413. };
  103414. ;
  103415. return SceneOptimization;
  103416. }());
  103417. BABYLON.SceneOptimization = SceneOptimization;
  103418. /**
  103419. * Defines an optimization used to reduce the size of render target textures
  103420. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103421. */
  103422. var TextureOptimization = /** @class */ (function (_super) {
  103423. __extends(TextureOptimization, _super);
  103424. /**
  103425. * Creates the TextureOptimization object
  103426. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103427. * @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
  103428. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103429. */
  103430. function TextureOptimization(
  103431. /**
  103432. * Defines the priority of this optimization (0 by default which means first in the list)
  103433. */
  103434. priority,
  103435. /**
  103436. * 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
  103437. */
  103438. maximumSize,
  103439. /**
  103440. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103441. */
  103442. step) {
  103443. if (priority === void 0) { priority = 0; }
  103444. if (maximumSize === void 0) { maximumSize = 1024; }
  103445. if (step === void 0) { step = 0.5; }
  103446. var _this = _super.call(this, priority) || this;
  103447. _this.priority = priority;
  103448. _this.maximumSize = maximumSize;
  103449. _this.step = step;
  103450. return _this;
  103451. }
  103452. /**
  103453. * Gets a string describing the action executed by the current optimization
  103454. * @returns description string
  103455. */
  103456. TextureOptimization.prototype.getDescription = function () {
  103457. return "Reducing render target texture size to " + this.maximumSize;
  103458. };
  103459. /**
  103460. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103461. * @param scene defines the current scene where to apply this optimization
  103462. * @param optimizer defines the current optimizer
  103463. * @returns true if everything that can be done was applied
  103464. */
  103465. TextureOptimization.prototype.apply = function (scene, optimizer) {
  103466. var allDone = true;
  103467. for (var index = 0; index < scene.textures.length; index++) {
  103468. var texture = scene.textures[index];
  103469. if (!texture.canRescale || texture.getContext) {
  103470. continue;
  103471. }
  103472. var currentSize = texture.getSize();
  103473. var maxDimension = Math.max(currentSize.width, currentSize.height);
  103474. if (maxDimension > this.maximumSize) {
  103475. texture.scale(this.step);
  103476. allDone = false;
  103477. }
  103478. }
  103479. return allDone;
  103480. };
  103481. return TextureOptimization;
  103482. }(SceneOptimization));
  103483. BABYLON.TextureOptimization = TextureOptimization;
  103484. /**
  103485. * Defines an optimization used to increase or decrease the rendering resolution
  103486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103487. */
  103488. var HardwareScalingOptimization = /** @class */ (function (_super) {
  103489. __extends(HardwareScalingOptimization, _super);
  103490. /**
  103491. * Creates the HardwareScalingOptimization object
  103492. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103493. * @param maximumScale defines the maximum scale to use (2 by default)
  103494. * @param step defines the step to use between two passes (0.5 by default)
  103495. */
  103496. function HardwareScalingOptimization(
  103497. /**
  103498. * Defines the priority of this optimization (0 by default which means first in the list)
  103499. */
  103500. priority,
  103501. /**
  103502. * Defines the maximum scale to use (2 by default)
  103503. */
  103504. maximumScale,
  103505. /**
  103506. * Defines the step to use between two passes (0.5 by default)
  103507. */
  103508. step) {
  103509. if (priority === void 0) { priority = 0; }
  103510. if (maximumScale === void 0) { maximumScale = 2; }
  103511. if (step === void 0) { step = 0.25; }
  103512. var _this = _super.call(this, priority) || this;
  103513. _this.priority = priority;
  103514. _this.maximumScale = maximumScale;
  103515. _this.step = step;
  103516. _this._currentScale = -1;
  103517. _this._directionOffset = 1;
  103518. return _this;
  103519. }
  103520. /**
  103521. * Gets a string describing the action executed by the current optimization
  103522. * @return description string
  103523. */
  103524. HardwareScalingOptimization.prototype.getDescription = function () {
  103525. return "Setting hardware scaling level to " + this._currentScale;
  103526. };
  103527. /**
  103528. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103529. * @param scene defines the current scene where to apply this optimization
  103530. * @param optimizer defines the current optimizer
  103531. * @returns true if everything that can be done was applied
  103532. */
  103533. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  103534. if (this._currentScale === -1) {
  103535. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  103536. if (this._currentScale > this.maximumScale) {
  103537. this._directionOffset = -1;
  103538. }
  103539. }
  103540. this._currentScale += this._directionOffset * this.step;
  103541. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  103542. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  103543. };
  103544. ;
  103545. return HardwareScalingOptimization;
  103546. }(SceneOptimization));
  103547. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  103548. /**
  103549. * Defines an optimization used to remove shadows
  103550. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103551. */
  103552. var ShadowsOptimization = /** @class */ (function (_super) {
  103553. __extends(ShadowsOptimization, _super);
  103554. function ShadowsOptimization() {
  103555. return _super !== null && _super.apply(this, arguments) || this;
  103556. }
  103557. /**
  103558. * Gets a string describing the action executed by the current optimization
  103559. * @return description string
  103560. */
  103561. ShadowsOptimization.prototype.getDescription = function () {
  103562. return "Turning shadows on/off";
  103563. };
  103564. /**
  103565. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103566. * @param scene defines the current scene where to apply this optimization
  103567. * @param optimizer defines the current optimizer
  103568. * @returns true if everything that can be done was applied
  103569. */
  103570. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  103571. scene.shadowsEnabled = optimizer.isInImprovementMode;
  103572. return true;
  103573. };
  103574. ;
  103575. return ShadowsOptimization;
  103576. }(SceneOptimization));
  103577. BABYLON.ShadowsOptimization = ShadowsOptimization;
  103578. /**
  103579. * Defines an optimization used to turn post-processes off
  103580. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103581. */
  103582. var PostProcessesOptimization = /** @class */ (function (_super) {
  103583. __extends(PostProcessesOptimization, _super);
  103584. function PostProcessesOptimization() {
  103585. return _super !== null && _super.apply(this, arguments) || this;
  103586. }
  103587. /**
  103588. * Gets a string describing the action executed by the current optimization
  103589. * @return description string
  103590. */
  103591. PostProcessesOptimization.prototype.getDescription = function () {
  103592. return "Turning post-processes on/off";
  103593. };
  103594. /**
  103595. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103596. * @param scene defines the current scene where to apply this optimization
  103597. * @param optimizer defines the current optimizer
  103598. * @returns true if everything that can be done was applied
  103599. */
  103600. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  103601. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  103602. return true;
  103603. };
  103604. ;
  103605. return PostProcessesOptimization;
  103606. }(SceneOptimization));
  103607. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  103608. /**
  103609. * Defines an optimization used to turn lens flares off
  103610. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103611. */
  103612. var LensFlaresOptimization = /** @class */ (function (_super) {
  103613. __extends(LensFlaresOptimization, _super);
  103614. function LensFlaresOptimization() {
  103615. return _super !== null && _super.apply(this, arguments) || this;
  103616. }
  103617. /**
  103618. * Gets a string describing the action executed by the current optimization
  103619. * @return description string
  103620. */
  103621. LensFlaresOptimization.prototype.getDescription = function () {
  103622. return "Turning lens flares on/off";
  103623. };
  103624. /**
  103625. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103626. * @param scene defines the current scene where to apply this optimization
  103627. * @param optimizer defines the current optimizer
  103628. * @returns true if everything that can be done was applied
  103629. */
  103630. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  103631. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  103632. return true;
  103633. };
  103634. ;
  103635. return LensFlaresOptimization;
  103636. }(SceneOptimization));
  103637. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  103638. /**
  103639. * Defines an optimization based on user defined callback.
  103640. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103641. */
  103642. var CustomOptimization = /** @class */ (function (_super) {
  103643. __extends(CustomOptimization, _super);
  103644. function CustomOptimization() {
  103645. return _super !== null && _super.apply(this, arguments) || this;
  103646. }
  103647. /**
  103648. * Gets a string describing the action executed by the current optimization
  103649. * @returns description string
  103650. */
  103651. CustomOptimization.prototype.getDescription = function () {
  103652. if (this.onGetDescription) {
  103653. return this.onGetDescription();
  103654. }
  103655. return "Running user defined callback";
  103656. };
  103657. /**
  103658. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103659. * @param scene defines the current scene where to apply this optimization
  103660. * @param optimizer defines the current optimizer
  103661. * @returns true if everything that can be done was applied
  103662. */
  103663. CustomOptimization.prototype.apply = function (scene, optimizer) {
  103664. if (this.onApply) {
  103665. return this.onApply(scene, optimizer);
  103666. }
  103667. return true;
  103668. };
  103669. ;
  103670. return CustomOptimization;
  103671. }(SceneOptimization));
  103672. BABYLON.CustomOptimization = CustomOptimization;
  103673. /**
  103674. * Defines an optimization used to turn particles off
  103675. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103676. */
  103677. var ParticlesOptimization = /** @class */ (function (_super) {
  103678. __extends(ParticlesOptimization, _super);
  103679. function ParticlesOptimization() {
  103680. return _super !== null && _super.apply(this, arguments) || this;
  103681. }
  103682. /**
  103683. * Gets a string describing the action executed by the current optimization
  103684. * @return description string
  103685. */
  103686. ParticlesOptimization.prototype.getDescription = function () {
  103687. return "Turning particles on/off";
  103688. };
  103689. /**
  103690. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103691. * @param scene defines the current scene where to apply this optimization
  103692. * @param optimizer defines the current optimizer
  103693. * @returns true if everything that can be done was applied
  103694. */
  103695. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  103696. scene.particlesEnabled = optimizer.isInImprovementMode;
  103697. return true;
  103698. };
  103699. ;
  103700. return ParticlesOptimization;
  103701. }(SceneOptimization));
  103702. BABYLON.ParticlesOptimization = ParticlesOptimization;
  103703. /**
  103704. * Defines an optimization used to turn render targets off
  103705. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103706. */
  103707. var RenderTargetsOptimization = /** @class */ (function (_super) {
  103708. __extends(RenderTargetsOptimization, _super);
  103709. function RenderTargetsOptimization() {
  103710. return _super !== null && _super.apply(this, arguments) || this;
  103711. }
  103712. /**
  103713. * Gets a string describing the action executed by the current optimization
  103714. * @return description string
  103715. */
  103716. RenderTargetsOptimization.prototype.getDescription = function () {
  103717. return "Turning render targets off";
  103718. };
  103719. /**
  103720. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103721. * @param scene defines the current scene where to apply this optimization
  103722. * @param optimizer defines the current optimizer
  103723. * @returns true if everything that can be done was applied
  103724. */
  103725. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  103726. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  103727. return true;
  103728. };
  103729. ;
  103730. return RenderTargetsOptimization;
  103731. }(SceneOptimization));
  103732. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  103733. /**
  103734. * Defines an optimization used to merge meshes with compatible materials
  103735. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103736. */
  103737. var MergeMeshesOptimization = /** @class */ (function (_super) {
  103738. __extends(MergeMeshesOptimization, _super);
  103739. function MergeMeshesOptimization() {
  103740. var _this = _super !== null && _super.apply(this, arguments) || this;
  103741. _this._canBeMerged = function (abstractMesh) {
  103742. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  103743. return false;
  103744. }
  103745. var mesh = abstractMesh;
  103746. if (mesh.isDisposed()) {
  103747. return false;
  103748. }
  103749. if (!mesh.isVisible || !mesh.isEnabled()) {
  103750. return false;
  103751. }
  103752. if (mesh.instances.length > 0) {
  103753. return false;
  103754. }
  103755. if (mesh.skeleton || mesh.hasLODLevels) {
  103756. return false;
  103757. }
  103758. return true;
  103759. };
  103760. return _this;
  103761. }
  103762. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  103763. /**
  103764. * Gets or sets a boolean which defines if optimization octree has to be updated
  103765. */
  103766. get: function () {
  103767. return MergeMeshesOptimization._UpdateSelectionTree;
  103768. },
  103769. /**
  103770. * Gets or sets a boolean which defines if optimization octree has to be updated
  103771. */
  103772. set: function (value) {
  103773. MergeMeshesOptimization._UpdateSelectionTree = value;
  103774. },
  103775. enumerable: true,
  103776. configurable: true
  103777. });
  103778. /**
  103779. * Gets a string describing the action executed by the current optimization
  103780. * @return description string
  103781. */
  103782. MergeMeshesOptimization.prototype.getDescription = function () {
  103783. return "Merging similar meshes together";
  103784. };
  103785. /**
  103786. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103787. * @param scene defines the current scene where to apply this optimization
  103788. * @param optimizer defines the current optimizer
  103789. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  103790. * @returns true if everything that can be done was applied
  103791. */
  103792. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  103793. var globalPool = scene.meshes.slice(0);
  103794. var globalLength = globalPool.length;
  103795. for (var index = 0; index < globalLength; index++) {
  103796. var currentPool = new Array();
  103797. var current = globalPool[index];
  103798. // Checks
  103799. if (!this._canBeMerged(current)) {
  103800. continue;
  103801. }
  103802. currentPool.push(current);
  103803. // Find compatible meshes
  103804. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  103805. var otherMesh = globalPool[subIndex];
  103806. if (!this._canBeMerged(otherMesh)) {
  103807. continue;
  103808. }
  103809. if (otherMesh.material !== current.material) {
  103810. continue;
  103811. }
  103812. if (otherMesh.checkCollisions !== current.checkCollisions) {
  103813. continue;
  103814. }
  103815. currentPool.push(otherMesh);
  103816. globalLength--;
  103817. globalPool.splice(subIndex, 1);
  103818. subIndex--;
  103819. }
  103820. if (currentPool.length < 2) {
  103821. continue;
  103822. }
  103823. // Merge meshes
  103824. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  103825. }
  103826. // Call the octree system optimization if it is defined.
  103827. var sceneAsAny = scene;
  103828. if (sceneAsAny.createOrUpdateSelectionOctree) {
  103829. if (updateSelectionTree != undefined) {
  103830. if (updateSelectionTree) {
  103831. sceneAsAny.createOrUpdateSelectionOctree();
  103832. }
  103833. }
  103834. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  103835. sceneAsAny.createOrUpdateSelectionOctree();
  103836. }
  103837. }
  103838. return true;
  103839. };
  103840. ;
  103841. MergeMeshesOptimization._UpdateSelectionTree = false;
  103842. return MergeMeshesOptimization;
  103843. }(SceneOptimization));
  103844. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  103845. /**
  103846. * Defines a list of options used by SceneOptimizer
  103847. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103848. */
  103849. var SceneOptimizerOptions = /** @class */ (function () {
  103850. /**
  103851. * Creates a new list of options used by SceneOptimizer
  103852. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  103853. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  103854. */
  103855. function SceneOptimizerOptions(
  103856. /**
  103857. * Defines the target frame rate to reach (60 by default)
  103858. */
  103859. targetFrameRate,
  103860. /**
  103861. * Defines the interval between two checkes (2000ms by default)
  103862. */
  103863. trackerDuration) {
  103864. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  103865. if (trackerDuration === void 0) { trackerDuration = 2000; }
  103866. this.targetFrameRate = targetFrameRate;
  103867. this.trackerDuration = trackerDuration;
  103868. /**
  103869. * Gets the list of optimizations to apply
  103870. */
  103871. this.optimizations = new Array();
  103872. }
  103873. /**
  103874. * Add a new optimization
  103875. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  103876. * @returns the current SceneOptimizerOptions
  103877. */
  103878. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  103879. this.optimizations.push(optimization);
  103880. return this;
  103881. };
  103882. /**
  103883. * Add a new custom optimization
  103884. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  103885. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  103886. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103887. * @returns the current SceneOptimizerOptions
  103888. */
  103889. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  103890. if (priority === void 0) { priority = 0; }
  103891. var optimization = new CustomOptimization(priority);
  103892. optimization.onApply = onApply;
  103893. optimization.onGetDescription = onGetDescription;
  103894. this.optimizations.push(optimization);
  103895. return this;
  103896. };
  103897. /**
  103898. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  103899. * @param targetFrameRate defines the target frame rate (60 by default)
  103900. * @returns a SceneOptimizerOptions object
  103901. */
  103902. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  103903. var result = new SceneOptimizerOptions(targetFrameRate);
  103904. var priority = 0;
  103905. result.addOptimization(new MergeMeshesOptimization(priority));
  103906. result.addOptimization(new ShadowsOptimization(priority));
  103907. result.addOptimization(new LensFlaresOptimization(priority));
  103908. // Next priority
  103909. priority++;
  103910. result.addOptimization(new PostProcessesOptimization(priority));
  103911. result.addOptimization(new ParticlesOptimization(priority));
  103912. // Next priority
  103913. priority++;
  103914. result.addOptimization(new TextureOptimization(priority, 1024));
  103915. return result;
  103916. };
  103917. /**
  103918. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  103919. * @param targetFrameRate defines the target frame rate (60 by default)
  103920. * @returns a SceneOptimizerOptions object
  103921. */
  103922. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  103923. var result = new SceneOptimizerOptions(targetFrameRate);
  103924. var priority = 0;
  103925. result.addOptimization(new MergeMeshesOptimization(priority));
  103926. result.addOptimization(new ShadowsOptimization(priority));
  103927. result.addOptimization(new LensFlaresOptimization(priority));
  103928. // Next priority
  103929. priority++;
  103930. result.addOptimization(new PostProcessesOptimization(priority));
  103931. result.addOptimization(new ParticlesOptimization(priority));
  103932. // Next priority
  103933. priority++;
  103934. result.addOptimization(new TextureOptimization(priority, 512));
  103935. // Next priority
  103936. priority++;
  103937. result.addOptimization(new RenderTargetsOptimization(priority));
  103938. // Next priority
  103939. priority++;
  103940. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  103941. return result;
  103942. };
  103943. /**
  103944. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  103945. * @param targetFrameRate defines the target frame rate (60 by default)
  103946. * @returns a SceneOptimizerOptions object
  103947. */
  103948. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  103949. var result = new SceneOptimizerOptions(targetFrameRate);
  103950. var priority = 0;
  103951. result.addOptimization(new MergeMeshesOptimization(priority));
  103952. result.addOptimization(new ShadowsOptimization(priority));
  103953. result.addOptimization(new LensFlaresOptimization(priority));
  103954. // Next priority
  103955. priority++;
  103956. result.addOptimization(new PostProcessesOptimization(priority));
  103957. result.addOptimization(new ParticlesOptimization(priority));
  103958. // Next priority
  103959. priority++;
  103960. result.addOptimization(new TextureOptimization(priority, 256));
  103961. // Next priority
  103962. priority++;
  103963. result.addOptimization(new RenderTargetsOptimization(priority));
  103964. // Next priority
  103965. priority++;
  103966. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  103967. return result;
  103968. };
  103969. return SceneOptimizerOptions;
  103970. }());
  103971. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  103972. /**
  103973. * Class used to run optimizations in order to reach a target frame rate
  103974. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103975. */
  103976. var SceneOptimizer = /** @class */ (function () {
  103977. /**
  103978. * Creates a new SceneOptimizer
  103979. * @param scene defines the scene to work on
  103980. * @param options defines the options to use with the SceneOptimizer
  103981. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  103982. * @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)
  103983. */
  103984. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  103985. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  103986. if (improvementMode === void 0) { improvementMode = false; }
  103987. var _this = this;
  103988. this._isRunning = false;
  103989. this._currentPriorityLevel = 0;
  103990. this._targetFrameRate = 60;
  103991. this._trackerDuration = 2000;
  103992. this._currentFrameRate = 0;
  103993. this._improvementMode = false;
  103994. /**
  103995. * Defines an observable called when the optimizer reaches the target frame rate
  103996. */
  103997. this.onSuccessObservable = new BABYLON.Observable();
  103998. /**
  103999. * Defines an observable called when the optimizer enables an optimization
  104000. */
  104001. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  104002. /**
  104003. * Defines an observable called when the optimizer is not able to reach the target frame rate
  104004. */
  104005. this.onFailureObservable = new BABYLON.Observable();
  104006. if (!options) {
  104007. this._options = new SceneOptimizerOptions();
  104008. }
  104009. else {
  104010. this._options = options;
  104011. }
  104012. if (this._options.targetFrameRate) {
  104013. this._targetFrameRate = this._options.targetFrameRate;
  104014. }
  104015. if (this._options.trackerDuration) {
  104016. this._trackerDuration = this._options.trackerDuration;
  104017. }
  104018. if (autoGeneratePriorities) {
  104019. var priority = 0;
  104020. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  104021. var optim = _a[_i];
  104022. optim.priority = priority++;
  104023. }
  104024. }
  104025. this._improvementMode = improvementMode;
  104026. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104027. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  104028. _this._sceneDisposeObserver = null;
  104029. _this.dispose();
  104030. });
  104031. }
  104032. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  104033. /**
  104034. * Gets a boolean indicating if the optimizer is in improvement mode
  104035. */
  104036. get: function () {
  104037. return this._improvementMode;
  104038. },
  104039. enumerable: true,
  104040. configurable: true
  104041. });
  104042. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  104043. /**
  104044. * Gets the current priority level (0 at start)
  104045. */
  104046. get: function () {
  104047. return this._currentPriorityLevel;
  104048. },
  104049. enumerable: true,
  104050. configurable: true
  104051. });
  104052. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  104053. /**
  104054. * Gets the current frame rate checked by the SceneOptimizer
  104055. */
  104056. get: function () {
  104057. return this._currentFrameRate;
  104058. },
  104059. enumerable: true,
  104060. configurable: true
  104061. });
  104062. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  104063. /**
  104064. * Gets or sets the current target frame rate (60 by default)
  104065. */
  104066. get: function () {
  104067. return this._targetFrameRate;
  104068. },
  104069. /**
  104070. * Gets or sets the current target frame rate (60 by default)
  104071. */
  104072. set: function (value) {
  104073. this._targetFrameRate = value;
  104074. },
  104075. enumerable: true,
  104076. configurable: true
  104077. });
  104078. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  104079. /**
  104080. * Gets or sets the current interval between two checks (every 2000ms by default)
  104081. */
  104082. get: function () {
  104083. return this._trackerDuration;
  104084. },
  104085. /**
  104086. * Gets or sets the current interval between two checks (every 2000ms by default)
  104087. */
  104088. set: function (value) {
  104089. this._trackerDuration = value;
  104090. },
  104091. enumerable: true,
  104092. configurable: true
  104093. });
  104094. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  104095. /**
  104096. * Gets the list of active optimizations
  104097. */
  104098. get: function () {
  104099. return this._options.optimizations;
  104100. },
  104101. enumerable: true,
  104102. configurable: true
  104103. });
  104104. /**
  104105. * Stops the current optimizer
  104106. */
  104107. SceneOptimizer.prototype.stop = function () {
  104108. this._isRunning = false;
  104109. };
  104110. /**
  104111. * Reset the optimizer to initial step (current priority level = 0)
  104112. */
  104113. SceneOptimizer.prototype.reset = function () {
  104114. this._currentPriorityLevel = 0;
  104115. };
  104116. /**
  104117. * Start the optimizer. By default it will try to reach a specific framerate
  104118. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  104119. */
  104120. SceneOptimizer.prototype.start = function () {
  104121. var _this = this;
  104122. if (this._isRunning) {
  104123. return;
  104124. }
  104125. this._isRunning = true;
  104126. // Let's wait for the scene to be ready before running our check
  104127. this._scene.executeWhenReady(function () {
  104128. setTimeout(function () {
  104129. _this._checkCurrentState();
  104130. }, _this._trackerDuration);
  104131. });
  104132. };
  104133. SceneOptimizer.prototype._checkCurrentState = function () {
  104134. var _this = this;
  104135. if (!this._isRunning) {
  104136. return;
  104137. }
  104138. var scene = this._scene;
  104139. var options = this._options;
  104140. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  104141. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  104142. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  104143. this._isRunning = false;
  104144. this.onSuccessObservable.notifyObservers(this);
  104145. return;
  104146. }
  104147. // Apply current level of optimizations
  104148. var allDone = true;
  104149. var noOptimizationApplied = true;
  104150. for (var index = 0; index < options.optimizations.length; index++) {
  104151. var optimization = options.optimizations[index];
  104152. if (optimization.priority === this._currentPriorityLevel) {
  104153. noOptimizationApplied = false;
  104154. allDone = allDone && optimization.apply(scene, this);
  104155. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  104156. }
  104157. }
  104158. // If no optimization was applied, this is a failure :(
  104159. if (noOptimizationApplied) {
  104160. this._isRunning = false;
  104161. this.onFailureObservable.notifyObservers(this);
  104162. return;
  104163. }
  104164. // If all optimizations were done, move to next level
  104165. if (allDone) {
  104166. this._currentPriorityLevel++;
  104167. }
  104168. // Let's the system running for a specific amount of time before checking FPS
  104169. scene.executeWhenReady(function () {
  104170. setTimeout(function () {
  104171. _this._checkCurrentState();
  104172. }, _this._trackerDuration);
  104173. });
  104174. };
  104175. /**
  104176. * Release all resources
  104177. */
  104178. SceneOptimizer.prototype.dispose = function () {
  104179. this.stop();
  104180. this.onSuccessObservable.clear();
  104181. this.onFailureObservable.clear();
  104182. this.onNewOptimizationAppliedObservable.clear();
  104183. if (this._sceneDisposeObserver) {
  104184. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  104185. }
  104186. };
  104187. /**
  104188. * Helper function to create a SceneOptimizer with one single line of code
  104189. * @param scene defines the scene to work on
  104190. * @param options defines the options to use with the SceneOptimizer
  104191. * @param onSuccess defines a callback to call on success
  104192. * @param onFailure defines a callback to call on failure
  104193. * @returns the new SceneOptimizer object
  104194. */
  104195. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  104196. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  104197. if (onSuccess) {
  104198. optimizer.onSuccessObservable.add(function () {
  104199. onSuccess();
  104200. });
  104201. }
  104202. if (onFailure) {
  104203. optimizer.onFailureObservable.add(function () {
  104204. onFailure();
  104205. });
  104206. }
  104207. optimizer.start();
  104208. return optimizer;
  104209. };
  104210. return SceneOptimizer;
  104211. }());
  104212. BABYLON.SceneOptimizer = SceneOptimizer;
  104213. })(BABYLON || (BABYLON = {}));
  104214. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  104215. var BABYLON;
  104216. (function (BABYLON) {
  104217. /**
  104218. * Gets the outline renderer associated with the scene
  104219. * @returns a OutlineRenderer
  104220. */
  104221. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  104222. if (!this._outlineRenderer) {
  104223. this._outlineRenderer = new OutlineRenderer(this);
  104224. }
  104225. return this._outlineRenderer;
  104226. };
  104227. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  104228. get: function () {
  104229. return this._renderOutline;
  104230. },
  104231. set: function (value) {
  104232. if (value) {
  104233. // Lazy Load the component.
  104234. this.getScene().getOutlineRenderer();
  104235. }
  104236. this._renderOutline = value;
  104237. },
  104238. enumerable: true,
  104239. configurable: true
  104240. });
  104241. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  104242. get: function () {
  104243. return this._renderOverlay;
  104244. },
  104245. set: function (value) {
  104246. if (value) {
  104247. // Lazy Load the component.
  104248. this.getScene().getOutlineRenderer();
  104249. }
  104250. this._renderOverlay = value;
  104251. },
  104252. enumerable: true,
  104253. configurable: true
  104254. });
  104255. /**
  104256. * This class is responsible to draw bothe outline/overlay of meshes.
  104257. * It should not be used directly but through the available method on mesh.
  104258. */
  104259. var OutlineRenderer = /** @class */ (function () {
  104260. /**
  104261. * Instantiates a new outline renderer. (There could be only one per scene).
  104262. * @param scene Defines the scene it belongs to
  104263. */
  104264. function OutlineRenderer(scene) {
  104265. /**
  104266. * The name of the component. Each component must have a unique name.
  104267. */
  104268. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  104269. /**
  104270. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  104271. */
  104272. this.zOffset = 1;
  104273. this.scene = scene;
  104274. this._engine = scene.getEngine();
  104275. this.scene._addComponent(this);
  104276. }
  104277. /**
  104278. * Register the component to one instance of a scene.
  104279. */
  104280. OutlineRenderer.prototype.register = function () {
  104281. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  104282. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  104283. };
  104284. /**
  104285. * Rebuilds the elements related to this component in case of
  104286. * context lost for instance.
  104287. */
  104288. OutlineRenderer.prototype.rebuild = function () {
  104289. // Nothing to do here.
  104290. };
  104291. /**
  104292. * Disposes the component and the associated ressources.
  104293. */
  104294. OutlineRenderer.prototype.dispose = function () {
  104295. // Nothing to do here.
  104296. };
  104297. /**
  104298. * Renders the outline in the canvas.
  104299. * @param subMesh Defines the sumesh to render
  104300. * @param batch Defines the batch of meshes in case of instances
  104301. * @param useOverlay Defines if the rendering is for the overlay or the outline
  104302. */
  104303. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  104304. var _this = this;
  104305. if (useOverlay === void 0) { useOverlay = false; }
  104306. var scene = this.scene;
  104307. var engine = scene.getEngine();
  104308. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104309. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  104310. return;
  104311. }
  104312. var mesh = subMesh.getRenderingMesh();
  104313. var material = subMesh.getMaterial();
  104314. if (!material || !scene.activeCamera) {
  104315. return;
  104316. }
  104317. engine.enableEffect(this._effect);
  104318. // Logarithmic depth
  104319. if (material.useLogarithmicDepth) {
  104320. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  104321. }
  104322. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  104323. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  104324. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  104325. // Bones
  104326. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104327. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104328. }
  104329. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  104330. // Alpha test
  104331. if (material && material.needAlphaTesting()) {
  104332. var alphaTexture = material.getAlphaTestTexture();
  104333. if (alphaTexture) {
  104334. this._effect.setTexture("diffuseSampler", alphaTexture);
  104335. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  104336. }
  104337. }
  104338. engine.setZOffset(-this.zOffset);
  104339. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  104340. engine.setZOffset(0);
  104341. };
  104342. /**
  104343. * Returns whether or not the outline renderer is ready for a given submesh.
  104344. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  104345. * @param subMesh Defines the submesh to check readyness for
  104346. * @param useInstances Defines wheter wee are trying to render instances or not
  104347. * @returns true if ready otherwise false
  104348. */
  104349. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  104350. var defines = [];
  104351. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  104352. var mesh = subMesh.getMesh();
  104353. var material = subMesh.getMaterial();
  104354. if (material) {
  104355. // Alpha test
  104356. if (material.needAlphaTesting()) {
  104357. defines.push("#define ALPHATEST");
  104358. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104359. attribs.push(BABYLON.VertexBuffer.UVKind);
  104360. defines.push("#define UV1");
  104361. }
  104362. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  104363. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104364. defines.push("#define UV2");
  104365. }
  104366. }
  104367. //Logarithmic depth
  104368. if (material.useLogarithmicDepth) {
  104369. defines.push("#define LOGARITHMICDEPTH");
  104370. }
  104371. }
  104372. // Bones
  104373. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104374. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104375. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104376. if (mesh.numBoneInfluencers > 4) {
  104377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104379. }
  104380. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104381. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  104382. }
  104383. else {
  104384. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104385. }
  104386. // Instances
  104387. if (useInstances) {
  104388. defines.push("#define INSTANCES");
  104389. attribs.push("world0");
  104390. attribs.push("world1");
  104391. attribs.push("world2");
  104392. attribs.push("world3");
  104393. }
  104394. // Get correct effect
  104395. var join = defines.join("\n");
  104396. if (this._cachedDefines !== join) {
  104397. this._cachedDefines = join;
  104398. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  104399. }
  104400. return this._effect.isReady();
  104401. };
  104402. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  104403. // Outline - step 1
  104404. this._savedDepthWrite = this._engine.getDepthWrite();
  104405. if (mesh.renderOutline) {
  104406. this._engine.setDepthWrite(false);
  104407. this.render(subMesh, batch);
  104408. this._engine.setDepthWrite(this._savedDepthWrite);
  104409. }
  104410. };
  104411. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  104412. // Outline - step 2
  104413. if (mesh.renderOutline && this._savedDepthWrite) {
  104414. this._engine.setDepthWrite(true);
  104415. this._engine.setColorWrite(false);
  104416. this.render(subMesh, batch);
  104417. this._engine.setColorWrite(true);
  104418. }
  104419. // Overlay
  104420. if (mesh.renderOverlay) {
  104421. var currentMode = this._engine.getAlphaMode();
  104422. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104423. this.render(subMesh, batch, true);
  104424. this._engine.setAlphaMode(currentMode);
  104425. }
  104426. };
  104427. return OutlineRenderer;
  104428. }());
  104429. BABYLON.OutlineRenderer = OutlineRenderer;
  104430. })(BABYLON || (BABYLON = {}));
  104431. //# sourceMappingURL=babylon.outlineRenderer.js.map
  104432. var BABYLON;
  104433. (function (BABYLON) {
  104434. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  104435. if (this._edgesRenderer) {
  104436. this._edgesRenderer.dispose();
  104437. this._edgesRenderer = null;
  104438. }
  104439. return this;
  104440. };
  104441. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104442. if (epsilon === void 0) { epsilon = 0.95; }
  104443. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104444. this.disableEdgesRendering();
  104445. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104446. return this;
  104447. };
  104448. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  104449. get: function () {
  104450. return this._edgesRenderer;
  104451. },
  104452. enumerable: true,
  104453. configurable: true
  104454. });
  104455. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104456. if (epsilon === void 0) { epsilon = 0.95; }
  104457. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104458. this.disableEdgesRendering();
  104459. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104460. return this;
  104461. };
  104462. /**
  104463. * FaceAdjacencies Helper class to generate edges
  104464. */
  104465. var FaceAdjacencies = /** @class */ (function () {
  104466. function FaceAdjacencies() {
  104467. this.edges = new Array();
  104468. this.edgesConnectedCount = 0;
  104469. }
  104470. return FaceAdjacencies;
  104471. }());
  104472. /**
  104473. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  104474. */
  104475. var EdgesRenderer = /** @class */ (function () {
  104476. /**
  104477. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  104478. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  104479. * @param source Mesh used to create edges
  104480. * @param epsilon sum of angles in adjacency to check for edge
  104481. * @param checkVerticesInsteadOfIndices
  104482. * @param generateEdgesLines - should generate Lines or only prepare resources.
  104483. */
  104484. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  104485. if (epsilon === void 0) { epsilon = 0.95; }
  104486. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104487. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  104488. var _this = this;
  104489. /**
  104490. * Define the size of the edges with an orthographic camera
  104491. */
  104492. this.edgesWidthScalerForOrthographic = 1000.0;
  104493. /**
  104494. * Define the size of the edges with a perspective camera
  104495. */
  104496. this.edgesWidthScalerForPerspective = 50.0;
  104497. this._linesPositions = new Array();
  104498. this._linesNormals = new Array();
  104499. this._linesIndices = new Array();
  104500. this._buffers = {};
  104501. this._checkVerticesInsteadOfIndices = false;
  104502. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  104503. this.isEnabled = true;
  104504. this._source = source;
  104505. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  104506. this._epsilon = epsilon;
  104507. this._prepareRessources();
  104508. if (generateEdgesLines) {
  104509. this._generateEdgesLines();
  104510. }
  104511. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  104512. _this._rebuild();
  104513. });
  104514. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  104515. _this.dispose();
  104516. });
  104517. }
  104518. EdgesRenderer.prototype._prepareRessources = function () {
  104519. if (this._lineShader) {
  104520. return;
  104521. }
  104522. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  104523. attributes: ["position", "normal"],
  104524. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  104525. });
  104526. this._lineShader.disableDepthWrite = true;
  104527. this._lineShader.backFaceCulling = false;
  104528. };
  104529. /** @hidden */
  104530. EdgesRenderer.prototype._rebuild = function () {
  104531. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104532. if (buffer) {
  104533. buffer._rebuild();
  104534. }
  104535. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104536. if (buffer) {
  104537. buffer._rebuild();
  104538. }
  104539. var scene = this._source.getScene();
  104540. var engine = scene.getEngine();
  104541. this._ib = engine.createIndexBuffer(this._linesIndices);
  104542. };
  104543. /**
  104544. * Releases the required resources for the edges renderer
  104545. */
  104546. EdgesRenderer.prototype.dispose = function () {
  104547. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  104548. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  104549. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104550. if (buffer) {
  104551. buffer.dispose();
  104552. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  104553. }
  104554. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104555. if (buffer) {
  104556. buffer.dispose();
  104557. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  104558. }
  104559. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  104560. this._lineShader.dispose();
  104561. };
  104562. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  104563. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  104564. return 0;
  104565. }
  104566. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  104567. return 1;
  104568. }
  104569. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  104570. return 2;
  104571. }
  104572. return -1;
  104573. };
  104574. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  104575. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  104576. return 0;
  104577. }
  104578. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  104579. return 1;
  104580. }
  104581. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  104582. return 2;
  104583. }
  104584. return -1;
  104585. };
  104586. /**
  104587. * Checks if the pair of p0 and p1 is en edge
  104588. * @param faceIndex
  104589. * @param edge
  104590. * @param faceNormals
  104591. * @param p0
  104592. * @param p1
  104593. * @private
  104594. */
  104595. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104596. var needToCreateLine;
  104597. if (edge === undefined) {
  104598. needToCreateLine = true;
  104599. }
  104600. else {
  104601. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  104602. needToCreateLine = dotProduct < this._epsilon;
  104603. }
  104604. if (needToCreateLine) {
  104605. var offset = this._linesPositions.length / 3;
  104606. var normal = p0.subtract(p1);
  104607. normal.normalize();
  104608. // Positions
  104609. this._linesPositions.push(p0.x);
  104610. this._linesPositions.push(p0.y);
  104611. this._linesPositions.push(p0.z);
  104612. this._linesPositions.push(p0.x);
  104613. this._linesPositions.push(p0.y);
  104614. this._linesPositions.push(p0.z);
  104615. this._linesPositions.push(p1.x);
  104616. this._linesPositions.push(p1.y);
  104617. this._linesPositions.push(p1.z);
  104618. this._linesPositions.push(p1.x);
  104619. this._linesPositions.push(p1.y);
  104620. this._linesPositions.push(p1.z);
  104621. // Normals
  104622. this._linesNormals.push(p1.x);
  104623. this._linesNormals.push(p1.y);
  104624. this._linesNormals.push(p1.z);
  104625. this._linesNormals.push(-1);
  104626. this._linesNormals.push(p1.x);
  104627. this._linesNormals.push(p1.y);
  104628. this._linesNormals.push(p1.z);
  104629. this._linesNormals.push(1);
  104630. this._linesNormals.push(p0.x);
  104631. this._linesNormals.push(p0.y);
  104632. this._linesNormals.push(p0.z);
  104633. this._linesNormals.push(-1);
  104634. this._linesNormals.push(p0.x);
  104635. this._linesNormals.push(p0.y);
  104636. this._linesNormals.push(p0.z);
  104637. this._linesNormals.push(1);
  104638. // Indices
  104639. this._linesIndices.push(offset);
  104640. this._linesIndices.push(offset + 1);
  104641. this._linesIndices.push(offset + 2);
  104642. this._linesIndices.push(offset);
  104643. this._linesIndices.push(offset + 2);
  104644. this._linesIndices.push(offset + 3);
  104645. }
  104646. };
  104647. /**
  104648. * Generates lines edges from adjacencjes
  104649. * @private
  104650. */
  104651. EdgesRenderer.prototype._generateEdgesLines = function () {
  104652. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104653. var indices = this._source.getIndices();
  104654. if (!indices || !positions) {
  104655. return;
  104656. }
  104657. // First let's find adjacencies
  104658. var adjacencies = new Array();
  104659. var faceNormals = new Array();
  104660. var index;
  104661. var faceAdjacencies;
  104662. // Prepare faces
  104663. for (index = 0; index < indices.length; index += 3) {
  104664. faceAdjacencies = new FaceAdjacencies();
  104665. var p0Index = indices[index];
  104666. var p1Index = indices[index + 1];
  104667. var p2Index = indices[index + 2];
  104668. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  104669. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  104670. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  104671. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  104672. faceNormal.normalize();
  104673. faceNormals.push(faceNormal);
  104674. adjacencies.push(faceAdjacencies);
  104675. }
  104676. // Scan
  104677. for (index = 0; index < adjacencies.length; index++) {
  104678. faceAdjacencies = adjacencies[index];
  104679. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  104680. var otherFaceAdjacencies = adjacencies[otherIndex];
  104681. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  104682. break;
  104683. }
  104684. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  104685. continue;
  104686. }
  104687. var otherP0 = indices[otherIndex * 3];
  104688. var otherP1 = indices[otherIndex * 3 + 1];
  104689. var otherP2 = indices[otherIndex * 3 + 2];
  104690. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  104691. var otherEdgeIndex = 0;
  104692. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  104693. continue;
  104694. }
  104695. switch (edgeIndex) {
  104696. case 0:
  104697. if (this._checkVerticesInsteadOfIndices) {
  104698. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104699. }
  104700. else {
  104701. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  104702. }
  104703. break;
  104704. case 1:
  104705. if (this._checkVerticesInsteadOfIndices) {
  104706. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104707. }
  104708. else {
  104709. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  104710. }
  104711. break;
  104712. case 2:
  104713. if (this._checkVerticesInsteadOfIndices) {
  104714. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104715. }
  104716. else {
  104717. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  104718. }
  104719. break;
  104720. }
  104721. if (otherEdgeIndex === -1) {
  104722. continue;
  104723. }
  104724. faceAdjacencies.edges[edgeIndex] = otherIndex;
  104725. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  104726. faceAdjacencies.edgesConnectedCount++;
  104727. otherFaceAdjacencies.edgesConnectedCount++;
  104728. if (faceAdjacencies.edgesConnectedCount === 3) {
  104729. break;
  104730. }
  104731. }
  104732. }
  104733. }
  104734. // Create lines
  104735. for (index = 0; index < adjacencies.length; index++) {
  104736. // 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
  104737. var current = adjacencies[index];
  104738. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104739. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  104740. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  104741. }
  104742. // Merge into a single mesh
  104743. var engine = this._source.getScene().getEngine();
  104744. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104745. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104746. this._ib = engine.createIndexBuffer(this._linesIndices);
  104747. this._indicesCount = this._linesIndices.length;
  104748. };
  104749. /**
  104750. * Checks wether or not the edges renderer is ready to render.
  104751. * @return true if ready, otherwise false.
  104752. */
  104753. EdgesRenderer.prototype.isReady = function () {
  104754. return this._lineShader.isReady();
  104755. };
  104756. /**
  104757. * Renders the edges of the attached mesh,
  104758. */
  104759. EdgesRenderer.prototype.render = function () {
  104760. var scene = this._source.getScene();
  104761. if (!this.isReady() || !scene.activeCamera) {
  104762. return;
  104763. }
  104764. var engine = scene.getEngine();
  104765. this._lineShader._preBind();
  104766. if (this._source.edgesColor.a !== 1) {
  104767. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104768. }
  104769. else {
  104770. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104771. }
  104772. // VBOs
  104773. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  104774. scene.resetCachedMaterial();
  104775. this._lineShader.setColor4("color", this._source.edgesColor);
  104776. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  104777. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  104778. }
  104779. else {
  104780. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  104781. }
  104782. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  104783. this._lineShader.bind(this._source.getWorldMatrix());
  104784. // Draw order
  104785. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  104786. this._lineShader.unbind();
  104787. };
  104788. return EdgesRenderer;
  104789. }());
  104790. BABYLON.EdgesRenderer = EdgesRenderer;
  104791. })(BABYLON || (BABYLON = {}));
  104792. //# sourceMappingURL=babylon.edgesRenderer.js.map
  104793. var BABYLON;
  104794. (function (BABYLON) {
  104795. /**
  104796. * FaceAdjacencies Helper class to generate edges
  104797. */
  104798. var FaceAdjacencies = /** @class */ (function () {
  104799. function FaceAdjacencies() {
  104800. this.edges = new Array();
  104801. this.edgesConnectedCount = 0;
  104802. }
  104803. return FaceAdjacencies;
  104804. }());
  104805. /**
  104806. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  104807. */
  104808. var LineEdgesRenderer = /** @class */ (function (_super) {
  104809. __extends(LineEdgesRenderer, _super);
  104810. /**
  104811. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  104812. * @param source LineMesh used to generate edges
  104813. * @param epsilon not important (specified angle for edge detection)
  104814. * @param checkVerticesInsteadOfIndices not important for LineMesh
  104815. */
  104816. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  104817. if (epsilon === void 0) { epsilon = 0.95; }
  104818. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104819. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  104820. _this._generateEdgesLines();
  104821. return _this;
  104822. }
  104823. /**
  104824. * Always create the edge since its a line so only important things are p0 and p1
  104825. * @param faceIndex not important for LineMesh
  104826. * @param edge not important for LineMesh
  104827. * @param faceNormals not important for LineMesh
  104828. * @param p0 beginnig of line
  104829. * @param p1 end of line
  104830. */
  104831. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104832. var offset = this._linesPositions.length / 3;
  104833. var normal = p0.subtract(p1);
  104834. normal.normalize();
  104835. // Positions
  104836. this._linesPositions.push(p0.x);
  104837. this._linesPositions.push(p0.y);
  104838. this._linesPositions.push(p0.z);
  104839. this._linesPositions.push(p0.x);
  104840. this._linesPositions.push(p0.y);
  104841. this._linesPositions.push(p0.z);
  104842. this._linesPositions.push(p1.x);
  104843. this._linesPositions.push(p1.y);
  104844. this._linesPositions.push(p1.z);
  104845. this._linesPositions.push(p1.x);
  104846. this._linesPositions.push(p1.y);
  104847. this._linesPositions.push(p1.z);
  104848. // Normals
  104849. this._linesNormals.push(p1.x);
  104850. this._linesNormals.push(p1.y);
  104851. this._linesNormals.push(p1.z);
  104852. this._linesNormals.push(-1);
  104853. this._linesNormals.push(p1.x);
  104854. this._linesNormals.push(p1.y);
  104855. this._linesNormals.push(p1.z);
  104856. this._linesNormals.push(1);
  104857. this._linesNormals.push(p0.x);
  104858. this._linesNormals.push(p0.y);
  104859. this._linesNormals.push(p0.z);
  104860. this._linesNormals.push(-1);
  104861. this._linesNormals.push(p0.x);
  104862. this._linesNormals.push(p0.y);
  104863. this._linesNormals.push(p0.z);
  104864. this._linesNormals.push(1);
  104865. // Indices
  104866. this._linesIndices.push(offset);
  104867. this._linesIndices.push(offset + 1);
  104868. this._linesIndices.push(offset + 2);
  104869. this._linesIndices.push(offset);
  104870. this._linesIndices.push(offset + 2);
  104871. this._linesIndices.push(offset + 3);
  104872. };
  104873. /**
  104874. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  104875. */
  104876. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  104877. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104878. var indices = this._source.getIndices();
  104879. if (!indices || !positions) {
  104880. return;
  104881. }
  104882. // First let's find adjacencies
  104883. var adjacencies = new Array();
  104884. var faceNormals = new Array();
  104885. var index;
  104886. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  104887. var currentAdjecancy = new FaceAdjacencies();
  104888. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  104889. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  104890. adjacencies.push(currentAdjecancy);
  104891. }
  104892. // Create lines
  104893. for (index = 0; index < adjacencies.length; index++) {
  104894. // 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
  104895. var current = adjacencies[index];
  104896. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104897. }
  104898. // Merge into a single mesh
  104899. var engine = this._source.getScene().getEngine();
  104900. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104901. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104902. this._ib = engine.createIndexBuffer(this._linesIndices);
  104903. this._indicesCount = this._linesIndices.length;
  104904. };
  104905. return LineEdgesRenderer;
  104906. }(BABYLON.EdgesRenderer));
  104907. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  104908. })(BABYLON || (BABYLON = {}));
  104909. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  104910. var BABYLON;
  104911. (function (BABYLON) {
  104912. // Adds the parser to the scene parsers.
  104913. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  104914. if (parsedData.effectLayers) {
  104915. if (!container.effectLayers) {
  104916. container.effectLayers = new Array();
  104917. }
  104918. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  104919. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  104920. container.effectLayers.push(effectLayer);
  104921. }
  104922. }
  104923. });
  104924. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  104925. var index = this.effectLayers.indexOf(toRemove);
  104926. if (index !== -1) {
  104927. this.effectLayers.splice(index, 1);
  104928. }
  104929. return index;
  104930. };
  104931. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  104932. this.effectLayers.push(newEffectLayer);
  104933. };
  104934. /**
  104935. * Defines the layer scene component responsible to manage any effect layers
  104936. * in a given scene.
  104937. */
  104938. var EffectLayerSceneComponent = /** @class */ (function () {
  104939. /**
  104940. * Creates a new instance of the component for the given scene
  104941. * @param scene Defines the scene to register the component in
  104942. */
  104943. function EffectLayerSceneComponent(scene) {
  104944. /**
  104945. * The component name helpfull to identify the component in the list of scene components.
  104946. */
  104947. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  104948. this._renderEffects = false;
  104949. this._needStencil = false;
  104950. this._previousStencilState = false;
  104951. this.scene = scene;
  104952. this._engine = scene.getEngine();
  104953. scene.effectLayers = new Array();
  104954. }
  104955. /**
  104956. * Registers the component in a given scene
  104957. */
  104958. EffectLayerSceneComponent.prototype.register = function () {
  104959. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  104960. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  104961. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  104962. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  104963. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  104964. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  104965. };
  104966. /**
  104967. * Rebuilds the elements related to this component in case of
  104968. * context lost for instance.
  104969. */
  104970. EffectLayerSceneComponent.prototype.rebuild = function () {
  104971. var layers = this.scene.effectLayers;
  104972. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104973. var effectLayer = layers_1[_i];
  104974. effectLayer._rebuild();
  104975. }
  104976. };
  104977. /**
  104978. * Serializes the component data to the specified json object
  104979. * @param serializationObject The object to serialize to
  104980. */
  104981. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  104982. // Effect layers
  104983. serializationObject.effectLayers = [];
  104984. var layers = this.scene.effectLayers;
  104985. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104986. var effectLayer = layers_2[_i];
  104987. if (effectLayer.serialize) {
  104988. serializationObject.effectLayers.push(effectLayer.serialize());
  104989. }
  104990. }
  104991. };
  104992. /**
  104993. * Adds all the element from the container to the scene
  104994. * @param container the container holding the elements
  104995. */
  104996. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  104997. var _this = this;
  104998. if (!container.effectLayers) {
  104999. return;
  105000. }
  105001. container.effectLayers.forEach(function (o) {
  105002. _this.scene.addEffectLayer(o);
  105003. });
  105004. };
  105005. /**
  105006. * Removes all the elements in the container from the scene
  105007. * @param container contains the elements to remove
  105008. */
  105009. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  105010. var _this = this;
  105011. if (!container.effectLayers) {
  105012. return;
  105013. }
  105014. container.effectLayers.forEach(function (o) {
  105015. _this.scene.removeEffectLayer(o);
  105016. });
  105017. };
  105018. /**
  105019. * Disposes the component and the associated ressources.
  105020. */
  105021. EffectLayerSceneComponent.prototype.dispose = function () {
  105022. var layers = this.scene.effectLayers;
  105023. while (layers.length) {
  105024. layers[0].dispose();
  105025. }
  105026. };
  105027. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  105028. var layers = this.scene.effectLayers;
  105029. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  105030. var layer = layers_3[_i];
  105031. if (!layer.hasMesh(mesh)) {
  105032. continue;
  105033. }
  105034. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  105035. var subMesh = _b[_a];
  105036. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  105037. return false;
  105038. }
  105039. }
  105040. }
  105041. return true;
  105042. };
  105043. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  105044. this._renderEffects = false;
  105045. this._needStencil = false;
  105046. var layers = this.scene.effectLayers;
  105047. if (layers && layers.length > 0) {
  105048. this._previousStencilState = this._engine.getStencilBuffer();
  105049. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  105050. var effectLayer = layers_4[_i];
  105051. if (effectLayer.shouldRender() &&
  105052. (!effectLayer.camera ||
  105053. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  105054. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  105055. this._renderEffects = true;
  105056. this._needStencil = this._needStencil || effectLayer.needStencil();
  105057. var renderTarget = effectLayer._mainTexture;
  105058. if (renderTarget._shouldRender()) {
  105059. this.scene.incrementRenderId();
  105060. renderTarget.render(false, false);
  105061. }
  105062. }
  105063. }
  105064. this.scene.incrementRenderId();
  105065. }
  105066. };
  105067. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  105068. // Activate effect Layer stencil
  105069. if (this._needStencil) {
  105070. this._engine.setStencilBuffer(true);
  105071. }
  105072. };
  105073. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  105074. // Restore effect Layer stencil
  105075. if (this._needStencil) {
  105076. this._engine.setStencilBuffer(this._previousStencilState);
  105077. }
  105078. };
  105079. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  105080. if (this._renderEffects) {
  105081. this._engine.setDepthBuffer(false);
  105082. var layers = this.scene.effectLayers;
  105083. for (var i = 0; i < layers.length; i++) {
  105084. var effectLayer = layers[i];
  105085. if (effectLayer.renderingGroupId === renderingGroupId) {
  105086. if (effectLayer.shouldRender()) {
  105087. effectLayer.render();
  105088. }
  105089. }
  105090. }
  105091. this._engine.setDepthBuffer(true);
  105092. }
  105093. };
  105094. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  105095. if (this._renderEffects) {
  105096. this._draw(-1);
  105097. }
  105098. };
  105099. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  105100. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  105101. this._draw(index);
  105102. }
  105103. };
  105104. return EffectLayerSceneComponent;
  105105. }());
  105106. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  105107. })(BABYLON || (BABYLON = {}));
  105108. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  105109. var __assign = (this && this.__assign) || function () {
  105110. __assign = Object.assign || function(t) {
  105111. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105112. s = arguments[i];
  105113. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105114. t[p] = s[p];
  105115. }
  105116. return t;
  105117. };
  105118. return __assign.apply(this, arguments);
  105119. };
  105120. var BABYLON;
  105121. (function (BABYLON) {
  105122. /**
  105123. * The effect layer Helps adding post process effect blended with the main pass.
  105124. *
  105125. * This can be for instance use to generate glow or higlight effects on the scene.
  105126. *
  105127. * The effect layer class can not be used directly and is intented to inherited from to be
  105128. * customized per effects.
  105129. */
  105130. var EffectLayer = /** @class */ (function () {
  105131. /**
  105132. * Instantiates a new effect Layer and references it in the scene.
  105133. * @param name The name of the layer
  105134. * @param scene The scene to use the layer in
  105135. */
  105136. function EffectLayer(
  105137. /** The Friendly of the effect in the scene */
  105138. name, scene) {
  105139. this._vertexBuffers = {};
  105140. this._maxSize = 0;
  105141. this._mainTextureDesiredSize = { width: 0, height: 0 };
  105142. this._shouldRender = true;
  105143. this._postProcesses = [];
  105144. this._textures = [];
  105145. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  105146. /**
  105147. * The clear color of the texture used to generate the glow map.
  105148. */
  105149. this.neutralColor = new BABYLON.Color4();
  105150. /**
  105151. * Specifies wether the highlight layer is enabled or not.
  105152. */
  105153. this.isEnabled = true;
  105154. /**
  105155. * An event triggered when the effect layer has been disposed.
  105156. */
  105157. this.onDisposeObservable = new BABYLON.Observable();
  105158. /**
  105159. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  105160. */
  105161. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  105162. /**
  105163. * An event triggered when the generated texture is being merged in the scene.
  105164. */
  105165. this.onBeforeComposeObservable = new BABYLON.Observable();
  105166. /**
  105167. * An event triggered when the generated texture has been merged in the scene.
  105168. */
  105169. this.onAfterComposeObservable = new BABYLON.Observable();
  105170. /**
  105171. * An event triggered when the efffect layer changes its size.
  105172. */
  105173. this.onSizeChangedObservable = new BABYLON.Observable();
  105174. this.name = name;
  105175. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105176. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  105177. if (!component) {
  105178. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  105179. this._scene._addComponent(component);
  105180. }
  105181. this._engine = this._scene.getEngine();
  105182. this._maxSize = this._engine.getCaps().maxTextureSize;
  105183. this._scene.effectLayers.push(this);
  105184. // Generate Buffers
  105185. this._generateIndexBuffer();
  105186. this._genrateVertexBuffer();
  105187. }
  105188. Object.defineProperty(EffectLayer.prototype, "camera", {
  105189. /**
  105190. * Gets the camera attached to the layer.
  105191. */
  105192. get: function () {
  105193. return this._effectLayerOptions.camera;
  105194. },
  105195. enumerable: true,
  105196. configurable: true
  105197. });
  105198. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  105199. /**
  105200. * Gets the rendering group id the layer should render in.
  105201. */
  105202. get: function () {
  105203. return this._effectLayerOptions.renderingGroupId;
  105204. },
  105205. enumerable: true,
  105206. configurable: true
  105207. });
  105208. /**
  105209. * Initializes the effect layer with the required options.
  105210. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  105211. */
  105212. EffectLayer.prototype._init = function (options) {
  105213. // Adapt options
  105214. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105215. this._setMainTextureSize();
  105216. this._createMainTexture();
  105217. this._createTextureAndPostProcesses();
  105218. this._mergeEffect = this._createMergeEffect();
  105219. };
  105220. /**
  105221. * Generates the index buffer of the full screen quad blending to the main canvas.
  105222. */
  105223. EffectLayer.prototype._generateIndexBuffer = function () {
  105224. // Indices
  105225. var indices = [];
  105226. indices.push(0);
  105227. indices.push(1);
  105228. indices.push(2);
  105229. indices.push(0);
  105230. indices.push(2);
  105231. indices.push(3);
  105232. this._indexBuffer = this._engine.createIndexBuffer(indices);
  105233. };
  105234. /**
  105235. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  105236. */
  105237. EffectLayer.prototype._genrateVertexBuffer = function () {
  105238. // VBO
  105239. var vertices = [];
  105240. vertices.push(1, 1);
  105241. vertices.push(-1, 1);
  105242. vertices.push(-1, -1);
  105243. vertices.push(1, -1);
  105244. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105245. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105246. };
  105247. /**
  105248. * Sets the main texture desired size which is the closest power of two
  105249. * of the engine canvas size.
  105250. */
  105251. EffectLayer.prototype._setMainTextureSize = function () {
  105252. if (this._effectLayerOptions.mainTextureFixedSize) {
  105253. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  105254. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  105255. }
  105256. else {
  105257. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  105258. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  105259. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  105260. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  105261. }
  105262. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  105263. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  105264. };
  105265. /**
  105266. * Creates the main texture for the effect layer.
  105267. */
  105268. EffectLayer.prototype._createMainTexture = function () {
  105269. var _this = this;
  105270. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  105271. width: this._mainTextureDesiredSize.width,
  105272. height: this._mainTextureDesiredSize.height
  105273. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105274. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  105275. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105276. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105277. this._mainTexture.anisotropicFilteringLevel = 1;
  105278. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105279. this._mainTexture.renderParticles = false;
  105280. this._mainTexture.renderList = null;
  105281. this._mainTexture.ignoreCameraViewport = true;
  105282. // Custom render function
  105283. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  105284. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  105285. var index;
  105286. var engine = _this._scene.getEngine();
  105287. if (depthOnlySubMeshes.length) {
  105288. engine.setColorWrite(false);
  105289. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  105290. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  105291. }
  105292. engine.setColorWrite(true);
  105293. }
  105294. for (index = 0; index < opaqueSubMeshes.length; index++) {
  105295. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  105296. }
  105297. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  105298. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  105299. }
  105300. for (index = 0; index < transparentSubMeshes.length; index++) {
  105301. _this._renderSubMesh(transparentSubMeshes.data[index]);
  105302. }
  105303. };
  105304. this._mainTexture.onClearObservable.add(function (engine) {
  105305. engine.clear(_this.neutralColor, true, true, true);
  105306. });
  105307. };
  105308. /**
  105309. * Checks for the readiness of the element composing the layer.
  105310. * @param subMesh the mesh to check for
  105311. * @param useInstances specify wether or not to use instances to render the mesh
  105312. * @param emissiveTexture the associated emissive texture used to generate the glow
  105313. * @return true if ready otherwise, false
  105314. */
  105315. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  105316. var material = subMesh.getMaterial();
  105317. if (!material) {
  105318. return false;
  105319. }
  105320. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  105321. return false;
  105322. }
  105323. var defines = [];
  105324. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105325. var mesh = subMesh.getMesh();
  105326. var uv1 = false;
  105327. var uv2 = false;
  105328. // Alpha test
  105329. if (material && material.needAlphaTesting()) {
  105330. var alphaTexture = material.getAlphaTestTexture();
  105331. if (alphaTexture) {
  105332. defines.push("#define ALPHATEST");
  105333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105334. alphaTexture.coordinatesIndex === 1) {
  105335. defines.push("#define DIFFUSEUV2");
  105336. uv2 = true;
  105337. }
  105338. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105339. defines.push("#define DIFFUSEUV1");
  105340. uv1 = true;
  105341. }
  105342. }
  105343. }
  105344. // Emissive
  105345. if (emissiveTexture) {
  105346. defines.push("#define EMISSIVE");
  105347. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105348. emissiveTexture.coordinatesIndex === 1) {
  105349. defines.push("#define EMISSIVEUV2");
  105350. uv2 = true;
  105351. }
  105352. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105353. defines.push("#define EMISSIVEUV1");
  105354. uv1 = true;
  105355. }
  105356. }
  105357. if (uv1) {
  105358. attribs.push(BABYLON.VertexBuffer.UVKind);
  105359. defines.push("#define UV1");
  105360. }
  105361. if (uv2) {
  105362. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105363. defines.push("#define UV2");
  105364. }
  105365. // Bones
  105366. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105367. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105368. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105369. if (mesh.numBoneInfluencers > 4) {
  105370. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105371. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105372. }
  105373. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105374. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  105375. }
  105376. else {
  105377. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105378. }
  105379. // Morph targets
  105380. var manager = mesh.morphTargetManager;
  105381. var morphInfluencers = 0;
  105382. if (manager) {
  105383. if (manager.numInfluencers > 0) {
  105384. defines.push("#define MORPHTARGETS");
  105385. morphInfluencers = manager.numInfluencers;
  105386. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  105387. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  105388. }
  105389. }
  105390. // Instances
  105391. if (useInstances) {
  105392. defines.push("#define INSTANCES");
  105393. attribs.push("world0");
  105394. attribs.push("world1");
  105395. attribs.push("world2");
  105396. attribs.push("world3");
  105397. }
  105398. // Get correct effect
  105399. var join = defines.join("\n");
  105400. if (this._cachedDefines !== join) {
  105401. this._cachedDefines = join;
  105402. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  105403. }
  105404. return this._effectLayerMapGenerationEffect.isReady();
  105405. };
  105406. /**
  105407. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  105408. */
  105409. EffectLayer.prototype.render = function () {
  105410. var currentEffect = this._mergeEffect;
  105411. // Check
  105412. if (!currentEffect.isReady())
  105413. return;
  105414. for (var i = 0; i < this._postProcesses.length; i++) {
  105415. if (!this._postProcesses[i].isReady()) {
  105416. return;
  105417. }
  105418. }
  105419. var engine = this._scene.getEngine();
  105420. this.onBeforeComposeObservable.notifyObservers(this);
  105421. // Render
  105422. engine.enableEffect(currentEffect);
  105423. engine.setState(false);
  105424. // VBOs
  105425. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105426. // Cache
  105427. var previousAlphaMode = engine.getAlphaMode();
  105428. // Go Blend.
  105429. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  105430. // Blends the map on the main canvas.
  105431. this._internalRender(currentEffect);
  105432. // Restore Alpha
  105433. engine.setAlphaMode(previousAlphaMode);
  105434. this.onAfterComposeObservable.notifyObservers(this);
  105435. // Handle size changes.
  105436. var size = this._mainTexture.getSize();
  105437. this._setMainTextureSize();
  105438. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  105439. // Recreate RTT and post processes on size change.
  105440. this.onSizeChangedObservable.notifyObservers(this);
  105441. this._disposeTextureAndPostProcesses();
  105442. this._createMainTexture();
  105443. this._createTextureAndPostProcesses();
  105444. }
  105445. };
  105446. /**
  105447. * Determine if a given mesh will be used in the current effect.
  105448. * @param mesh mesh to test
  105449. * @returns true if the mesh will be used
  105450. */
  105451. EffectLayer.prototype.hasMesh = function (mesh) {
  105452. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  105453. return true;
  105454. }
  105455. return false;
  105456. };
  105457. /**
  105458. * Returns true if the layer contains information to display, otherwise false.
  105459. * @returns true if the glow layer should be rendered
  105460. */
  105461. EffectLayer.prototype.shouldRender = function () {
  105462. return this.isEnabled && this._shouldRender;
  105463. };
  105464. /**
  105465. * Returns true if the mesh should render, otherwise false.
  105466. * @param mesh The mesh to render
  105467. * @returns true if it should render otherwise false
  105468. */
  105469. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  105470. return true;
  105471. };
  105472. /**
  105473. * Returns true if the mesh should render, otherwise false.
  105474. * @param mesh The mesh to render
  105475. * @returns true if it should render otherwise false
  105476. */
  105477. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  105478. return true;
  105479. };
  105480. /**
  105481. * Renders the submesh passed in parameter to the generation map.
  105482. */
  105483. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  105484. var _this = this;
  105485. if (!this.shouldRender()) {
  105486. return;
  105487. }
  105488. var material = subMesh.getMaterial();
  105489. var mesh = subMesh.getRenderingMesh();
  105490. var scene = this._scene;
  105491. var engine = scene.getEngine();
  105492. if (!material) {
  105493. return;
  105494. }
  105495. // Do not block in blend mode.
  105496. if (material.needAlphaBlendingForMesh(mesh)) {
  105497. return;
  105498. }
  105499. // Culling
  105500. engine.setState(material.backFaceCulling);
  105501. // Managing instances
  105502. var batch = mesh._getInstancesRenderList(subMesh._id);
  105503. if (batch.mustReturn) {
  105504. return;
  105505. }
  105506. // Early Exit per mesh
  105507. if (!this._shouldRenderMesh(mesh)) {
  105508. return;
  105509. }
  105510. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  105511. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  105512. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  105513. engine.enableEffect(this._effectLayerMapGenerationEffect);
  105514. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  105515. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  105516. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  105517. // Alpha test
  105518. if (material && material.needAlphaTesting()) {
  105519. var alphaTexture = material.getAlphaTestTexture();
  105520. if (alphaTexture) {
  105521. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  105522. var textureMatrix = alphaTexture.getTextureMatrix();
  105523. if (textureMatrix) {
  105524. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  105525. }
  105526. }
  105527. }
  105528. // Glow emissive only
  105529. if (this._emissiveTextureAndColor.texture) {
  105530. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  105531. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  105532. }
  105533. // Bones
  105534. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  105535. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  105536. }
  105537. // Morph targets
  105538. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  105539. // Draw
  105540. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  105541. }
  105542. else {
  105543. // Need to reset refresh rate of the main map
  105544. this._mainTexture.resetRefreshCounter();
  105545. }
  105546. };
  105547. /**
  105548. * Rebuild the required buffers.
  105549. * @hidden Internal use only.
  105550. */
  105551. EffectLayer.prototype._rebuild = function () {
  105552. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105553. if (vb) {
  105554. vb._rebuild();
  105555. }
  105556. this._generateIndexBuffer();
  105557. };
  105558. /**
  105559. * Dispose only the render target textures and post process.
  105560. */
  105561. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  105562. this._mainTexture.dispose();
  105563. for (var i = 0; i < this._postProcesses.length; i++) {
  105564. if (this._postProcesses[i]) {
  105565. this._postProcesses[i].dispose();
  105566. }
  105567. }
  105568. this._postProcesses = [];
  105569. for (var i = 0; i < this._textures.length; i++) {
  105570. if (this._textures[i]) {
  105571. this._textures[i].dispose();
  105572. }
  105573. }
  105574. this._textures = [];
  105575. };
  105576. /**
  105577. * Dispose the highlight layer and free resources.
  105578. */
  105579. EffectLayer.prototype.dispose = function () {
  105580. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105581. if (vertexBuffer) {
  105582. vertexBuffer.dispose();
  105583. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105584. }
  105585. if (this._indexBuffer) {
  105586. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105587. this._indexBuffer = null;
  105588. }
  105589. // Clean textures and post processes
  105590. this._disposeTextureAndPostProcesses();
  105591. // Remove from scene
  105592. var index = this._scene.effectLayers.indexOf(this, 0);
  105593. if (index > -1) {
  105594. this._scene.effectLayers.splice(index, 1);
  105595. }
  105596. // Callback
  105597. this.onDisposeObservable.notifyObservers(this);
  105598. this.onDisposeObservable.clear();
  105599. this.onBeforeRenderMainTextureObservable.clear();
  105600. this.onBeforeComposeObservable.clear();
  105601. this.onAfterComposeObservable.clear();
  105602. this.onSizeChangedObservable.clear();
  105603. };
  105604. /**
  105605. * Gets the class name of the effect layer
  105606. * @returns the string with the class name of the effect layer
  105607. */
  105608. EffectLayer.prototype.getClassName = function () {
  105609. return "EffectLayer";
  105610. };
  105611. /**
  105612. * Creates an effect layer from parsed effect layer data
  105613. * @param parsedEffectLayer defines effect layer data
  105614. * @param scene defines the current scene
  105615. * @param rootUrl defines the root URL containing the effect layer information
  105616. * @returns a parsed effect Layer
  105617. */
  105618. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  105619. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  105620. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  105621. };
  105622. __decorate([
  105623. BABYLON.serialize()
  105624. ], EffectLayer.prototype, "name", void 0);
  105625. __decorate([
  105626. BABYLON.serializeAsColor4()
  105627. ], EffectLayer.prototype, "neutralColor", void 0);
  105628. __decorate([
  105629. BABYLON.serialize()
  105630. ], EffectLayer.prototype, "isEnabled", void 0);
  105631. __decorate([
  105632. BABYLON.serializeAsCameraReference()
  105633. ], EffectLayer.prototype, "camera", null);
  105634. __decorate([
  105635. BABYLON.serialize()
  105636. ], EffectLayer.prototype, "renderingGroupId", null);
  105637. return EffectLayer;
  105638. }());
  105639. BABYLON.EffectLayer = EffectLayer;
  105640. })(BABYLON || (BABYLON = {}));
  105641. //# sourceMappingURL=babylon.effectLayer.js.map
  105642. var BABYLON;
  105643. (function (BABYLON) {
  105644. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  105645. for (var index = 0; index < this.effectLayers.length; index++) {
  105646. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  105647. return this.effectLayers[index];
  105648. }
  105649. }
  105650. return null;
  105651. };
  105652. /**
  105653. * Special Glow Blur post process only blurring the alpha channel
  105654. * It enforces keeping the most luminous color in the color channel.
  105655. */
  105656. var GlowBlurPostProcess = /** @class */ (function (_super) {
  105657. __extends(GlowBlurPostProcess, _super);
  105658. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  105659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  105660. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  105661. _this.direction = direction;
  105662. _this.kernel = kernel;
  105663. _this.onApplyObservable.add(function (effect) {
  105664. effect.setFloat2("screenSize", _this.width, _this.height);
  105665. effect.setVector2("direction", _this.direction);
  105666. effect.setFloat("blurWidth", _this.kernel);
  105667. });
  105668. return _this;
  105669. }
  105670. return GlowBlurPostProcess;
  105671. }(BABYLON.PostProcess));
  105672. /**
  105673. * The highlight layer Helps adding a glow effect around a mesh.
  105674. *
  105675. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105676. * glowy meshes to your scene.
  105677. *
  105678. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  105679. */
  105680. var HighlightLayer = /** @class */ (function (_super) {
  105681. __extends(HighlightLayer, _super);
  105682. /**
  105683. * Instantiates a new highlight Layer and references it to the scene..
  105684. * @param name The name of the layer
  105685. * @param scene The scene to use the layer in
  105686. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  105687. */
  105688. function HighlightLayer(name, scene, options) {
  105689. var _this = _super.call(this, name, scene) || this;
  105690. _this.name = name;
  105691. /**
  105692. * Specifies whether or not the inner glow is ACTIVE in the layer.
  105693. */
  105694. _this.innerGlow = true;
  105695. /**
  105696. * Specifies whether or not the outer glow is ACTIVE in the layer.
  105697. */
  105698. _this.outerGlow = true;
  105699. /**
  105700. * An event triggered when the highlight layer is being blurred.
  105701. */
  105702. _this.onBeforeBlurObservable = new BABYLON.Observable();
  105703. /**
  105704. * An event triggered when the highlight layer has been blurred.
  105705. */
  105706. _this.onAfterBlurObservable = new BABYLON.Observable();
  105707. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  105708. _this._meshes = {};
  105709. _this._excludedMeshes = {};
  105710. _this.neutralColor = HighlightLayer.NeutralColor;
  105711. // Warn on stencil
  105712. if (!_this._engine.isStencilEnable) {
  105713. 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 }");
  105714. }
  105715. // Adapt options
  105716. _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);
  105717. // Initialize the layer
  105718. _this._init({
  105719. alphaBlendingMode: _this._options.alphaBlendingMode,
  105720. camera: _this._options.camera,
  105721. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105722. mainTextureRatio: _this._options.mainTextureRatio,
  105723. renderingGroupId: _this._options.renderingGroupId
  105724. });
  105725. // Do not render as long as no meshes have been added
  105726. _this._shouldRender = false;
  105727. return _this;
  105728. }
  105729. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  105730. /**
  105731. * Gets the horizontal size of the blur.
  105732. */
  105733. get: function () {
  105734. return this._horizontalBlurPostprocess.kernel;
  105735. },
  105736. /**
  105737. * Specifies the horizontal size of the blur.
  105738. */
  105739. set: function (value) {
  105740. this._horizontalBlurPostprocess.kernel = value;
  105741. },
  105742. enumerable: true,
  105743. configurable: true
  105744. });
  105745. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  105746. /**
  105747. * Gets the vertical size of the blur.
  105748. */
  105749. get: function () {
  105750. return this._verticalBlurPostprocess.kernel;
  105751. },
  105752. /**
  105753. * Specifies the vertical size of the blur.
  105754. */
  105755. set: function (value) {
  105756. this._verticalBlurPostprocess.kernel = value;
  105757. },
  105758. enumerable: true,
  105759. configurable: true
  105760. });
  105761. /**
  105762. * Get the effect name of the layer.
  105763. * @return The effect name
  105764. */
  105765. HighlightLayer.prototype.getEffectName = function () {
  105766. return HighlightLayer.EffectName;
  105767. };
  105768. /**
  105769. * Create the merge effect. This is the shader use to blit the information back
  105770. * to the main canvas at the end of the scene rendering.
  105771. */
  105772. HighlightLayer.prototype._createMergeEffect = function () {
  105773. // Effect
  105774. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  105775. };
  105776. /**
  105777. * Creates the render target textures and post processes used in the highlight layer.
  105778. */
  105779. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  105780. var _this = this;
  105781. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  105782. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  105783. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105784. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105785. var textureType = 0;
  105786. if (this._engine.getCaps().textureHalfFloatRender) {
  105787. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105788. }
  105789. else {
  105790. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105791. }
  105792. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  105793. width: blurTextureWidth,
  105794. height: blurTextureHeight
  105795. }, this._scene, false, true, textureType);
  105796. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105797. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105798. this._blurTexture.anisotropicFilteringLevel = 16;
  105799. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  105800. this._blurTexture.renderParticles = false;
  105801. this._blurTexture.ignoreCameraViewport = true;
  105802. this._textures = [this._blurTexture];
  105803. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  105804. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105805. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  105806. effect.setTexture("textureSampler", _this._mainTexture);
  105807. });
  105808. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105809. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105810. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105811. });
  105812. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105813. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  105814. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105815. });
  105816. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105817. }
  105818. else {
  105819. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  105820. width: blurTextureWidth,
  105821. height: blurTextureHeight
  105822. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105823. this._horizontalBlurPostprocess.width = blurTextureWidth;
  105824. this._horizontalBlurPostprocess.height = blurTextureHeight;
  105825. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105826. effect.setTexture("textureSampler", _this._mainTexture);
  105827. });
  105828. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  105829. width: blurTextureWidth,
  105830. height: blurTextureHeight
  105831. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105832. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105833. }
  105834. this._mainTexture.onAfterUnbindObservable.add(function () {
  105835. _this.onBeforeBlurObservable.notifyObservers(_this);
  105836. var internalTexture = _this._blurTexture.getInternalTexture();
  105837. if (internalTexture) {
  105838. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  105839. }
  105840. _this.onAfterBlurObservable.notifyObservers(_this);
  105841. });
  105842. // Prevent autoClear.
  105843. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105844. };
  105845. /**
  105846. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105847. */
  105848. HighlightLayer.prototype.needStencil = function () {
  105849. return true;
  105850. };
  105851. /**
  105852. * Checks for the readiness of the element composing the layer.
  105853. * @param subMesh the mesh to check for
  105854. * @param useInstances specify wether or not to use instances to render the mesh
  105855. * @param emissiveTexture the associated emissive texture used to generate the glow
  105856. * @return true if ready otherwise, false
  105857. */
  105858. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  105859. var material = subMesh.getMaterial();
  105860. var mesh = subMesh.getRenderingMesh();
  105861. if (!material || !mesh || !this._meshes) {
  105862. return false;
  105863. }
  105864. var emissiveTexture = null;
  105865. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105866. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105867. emissiveTexture = material.emissiveTexture;
  105868. }
  105869. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105870. };
  105871. /**
  105872. * Implementation specific of rendering the generating effect on the main canvas.
  105873. * @param effect The effect used to render through
  105874. */
  105875. HighlightLayer.prototype._internalRender = function (effect) {
  105876. // Texture
  105877. effect.setTexture("textureSampler", this._blurTexture);
  105878. // Cache
  105879. var engine = this._engine;
  105880. var previousStencilBuffer = engine.getStencilBuffer();
  105881. var previousStencilFunction = engine.getStencilFunction();
  105882. var previousStencilMask = engine.getStencilMask();
  105883. var previousStencilOperationPass = engine.getStencilOperationPass();
  105884. var previousStencilOperationFail = engine.getStencilOperationFail();
  105885. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  105886. var previousStencilReference = engine.getStencilFunctionReference();
  105887. // Stencil operations
  105888. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  105889. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  105890. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  105891. // Draw order
  105892. engine.setStencilMask(0x00);
  105893. engine.setStencilBuffer(true);
  105894. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  105895. // 2 passes inner outer
  105896. if (this.outerGlow) {
  105897. effect.setFloat("offset", 0);
  105898. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  105899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105900. }
  105901. if (this.innerGlow) {
  105902. effect.setFloat("offset", 1);
  105903. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  105904. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105905. }
  105906. // Restore Cache
  105907. engine.setStencilFunction(previousStencilFunction);
  105908. engine.setStencilMask(previousStencilMask);
  105909. engine.setStencilBuffer(previousStencilBuffer);
  105910. engine.setStencilOperationPass(previousStencilOperationPass);
  105911. engine.setStencilOperationFail(previousStencilOperationFail);
  105912. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  105913. engine.setStencilFunctionReference(previousStencilReference);
  105914. };
  105915. /**
  105916. * Returns true if the layer contains information to display, otherwise false.
  105917. */
  105918. HighlightLayer.prototype.shouldRender = function () {
  105919. if (_super.prototype.shouldRender.call(this)) {
  105920. return this._meshes ? true : false;
  105921. }
  105922. return false;
  105923. };
  105924. /**
  105925. * Returns true if the mesh should render, otherwise false.
  105926. * @param mesh The mesh to render
  105927. * @returns true if it should render otherwise false
  105928. */
  105929. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  105930. // Excluded Mesh
  105931. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  105932. return false;
  105933. }
  105934. ;
  105935. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105936. return false;
  105937. }
  105938. return true;
  105939. };
  105940. /**
  105941. * Sets the required values for both the emissive texture and and the main color.
  105942. */
  105943. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105944. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105945. if (highlightLayerMesh) {
  105946. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  105947. }
  105948. else {
  105949. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105950. }
  105951. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105952. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105953. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  105954. }
  105955. else {
  105956. this._emissiveTextureAndColor.texture = null;
  105957. }
  105958. };
  105959. /**
  105960. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  105961. * @param mesh The mesh to exclude from the highlight layer
  105962. */
  105963. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  105964. if (!this._excludedMeshes) {
  105965. return;
  105966. }
  105967. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105968. if (!meshExcluded) {
  105969. this._excludedMeshes[mesh.uniqueId] = {
  105970. mesh: mesh,
  105971. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  105972. mesh.getEngine().setStencilBuffer(false);
  105973. }),
  105974. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  105975. mesh.getEngine().setStencilBuffer(true);
  105976. }),
  105977. };
  105978. }
  105979. };
  105980. /**
  105981. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  105982. * @param mesh The mesh to highlight
  105983. */
  105984. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  105985. if (!this._excludedMeshes) {
  105986. return;
  105987. }
  105988. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105989. if (meshExcluded) {
  105990. if (meshExcluded.beforeRender) {
  105991. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  105992. }
  105993. if (meshExcluded.afterRender) {
  105994. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  105995. }
  105996. }
  105997. this._excludedMeshes[mesh.uniqueId] = null;
  105998. };
  105999. /**
  106000. * Determine if a given mesh will be highlighted by the current HighlightLayer
  106001. * @param mesh mesh to test
  106002. * @returns true if the mesh will be highlighted by the current HighlightLayer
  106003. */
  106004. HighlightLayer.prototype.hasMesh = function (mesh) {
  106005. if (!this._meshes) {
  106006. return false;
  106007. }
  106008. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106009. return false;
  106010. }
  106011. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  106012. };
  106013. /**
  106014. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  106015. * @param mesh The mesh to highlight
  106016. * @param color The color of the highlight
  106017. * @param glowEmissiveOnly Extract the glow from the emissive texture
  106018. */
  106019. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  106020. var _this = this;
  106021. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  106022. if (!this._meshes) {
  106023. return;
  106024. }
  106025. var meshHighlight = this._meshes[mesh.uniqueId];
  106026. if (meshHighlight) {
  106027. meshHighlight.color = color;
  106028. }
  106029. else {
  106030. this._meshes[mesh.uniqueId] = {
  106031. mesh: mesh,
  106032. color: color,
  106033. // Lambda required for capture due to Observable this context
  106034. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  106035. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  106036. _this._defaultStencilReference(mesh);
  106037. }
  106038. else {
  106039. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  106040. }
  106041. }),
  106042. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  106043. glowEmissiveOnly: glowEmissiveOnly
  106044. };
  106045. mesh.onDisposeObservable.add(function () {
  106046. _this._disposeMesh(mesh);
  106047. });
  106048. }
  106049. this._shouldRender = true;
  106050. };
  106051. /**
  106052. * Remove a mesh from the highlight layer in order to make it stop glowing.
  106053. * @param mesh The mesh to highlight
  106054. */
  106055. HighlightLayer.prototype.removeMesh = function (mesh) {
  106056. if (!this._meshes) {
  106057. return;
  106058. }
  106059. var meshHighlight = this._meshes[mesh.uniqueId];
  106060. if (meshHighlight) {
  106061. if (meshHighlight.observerHighlight) {
  106062. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106063. }
  106064. if (meshHighlight.observerDefault) {
  106065. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106066. }
  106067. delete this._meshes[mesh.uniqueId];
  106068. }
  106069. this._shouldRender = false;
  106070. for (var meshHighlightToCheck in this._meshes) {
  106071. if (this._meshes[meshHighlightToCheck]) {
  106072. this._shouldRender = true;
  106073. break;
  106074. }
  106075. }
  106076. };
  106077. /**
  106078. * Force the stencil to the normal expected value for none glowing parts
  106079. */
  106080. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  106081. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  106082. };
  106083. /**
  106084. * Free any resources and references associated to a mesh.
  106085. * Internal use
  106086. * @param mesh The mesh to free.
  106087. * @hidden
  106088. */
  106089. HighlightLayer.prototype._disposeMesh = function (mesh) {
  106090. this.removeMesh(mesh);
  106091. this.removeExcludedMesh(mesh);
  106092. };
  106093. /**
  106094. * Dispose the highlight layer and free resources.
  106095. */
  106096. HighlightLayer.prototype.dispose = function () {
  106097. if (this._meshes) {
  106098. // Clean mesh references
  106099. for (var id in this._meshes) {
  106100. var meshHighlight = this._meshes[id];
  106101. if (meshHighlight && meshHighlight.mesh) {
  106102. if (meshHighlight.observerHighlight) {
  106103. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106104. }
  106105. if (meshHighlight.observerDefault) {
  106106. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106107. }
  106108. }
  106109. }
  106110. this._meshes = null;
  106111. }
  106112. if (this._excludedMeshes) {
  106113. for (var id in this._excludedMeshes) {
  106114. var meshHighlight = this._excludedMeshes[id];
  106115. if (meshHighlight) {
  106116. if (meshHighlight.beforeRender) {
  106117. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  106118. }
  106119. if (meshHighlight.afterRender) {
  106120. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  106121. }
  106122. }
  106123. }
  106124. this._excludedMeshes = null;
  106125. }
  106126. _super.prototype.dispose.call(this);
  106127. };
  106128. /**
  106129. * Gets the class name of the effect layer
  106130. * @returns the string with the class name of the effect layer
  106131. */
  106132. HighlightLayer.prototype.getClassName = function () {
  106133. return "HighlightLayer";
  106134. };
  106135. /**
  106136. * Serializes this Highlight layer
  106137. * @returns a serialized Highlight layer object
  106138. */
  106139. HighlightLayer.prototype.serialize = function () {
  106140. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106141. serializationObject.customType = "BABYLON.HighlightLayer";
  106142. // Highlighted meshes
  106143. serializationObject.meshes = [];
  106144. if (this._meshes) {
  106145. for (var m in this._meshes) {
  106146. var mesh = this._meshes[m];
  106147. if (mesh) {
  106148. serializationObject.meshes.push({
  106149. glowEmissiveOnly: mesh.glowEmissiveOnly,
  106150. color: mesh.color.asArray(),
  106151. meshId: mesh.mesh.id
  106152. });
  106153. }
  106154. }
  106155. }
  106156. // Excluded meshes
  106157. serializationObject.excludedMeshes = [];
  106158. if (this._excludedMeshes) {
  106159. for (var e in this._excludedMeshes) {
  106160. var excludedMesh = this._excludedMeshes[e];
  106161. if (excludedMesh) {
  106162. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  106163. }
  106164. }
  106165. }
  106166. return serializationObject;
  106167. };
  106168. /**
  106169. * Creates a Highlight layer from parsed Highlight layer data
  106170. * @param parsedHightlightLayer defines the Highlight layer data
  106171. * @param scene defines the current scene
  106172. * @param rootUrl defines the root URL containing the Highlight layer information
  106173. * @returns a parsed Highlight layer
  106174. */
  106175. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  106176. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  106177. var index;
  106178. // Excluded meshes
  106179. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  106180. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  106181. if (mesh) {
  106182. hl.addExcludedMesh(mesh);
  106183. }
  106184. }
  106185. // Included meshes
  106186. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  106187. var highlightedMesh = parsedHightlightLayer.meshes[index];
  106188. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  106189. if (mesh) {
  106190. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  106191. }
  106192. }
  106193. return hl;
  106194. };
  106195. /**
  106196. * Effect Name of the highlight layer.
  106197. */
  106198. HighlightLayer.EffectName = "HighlightLayer";
  106199. /**
  106200. * The neutral color used during the preparation of the glow effect.
  106201. * This is black by default as the blend operation is a blend operation.
  106202. */
  106203. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  106204. /**
  106205. * Stencil value used for glowing meshes.
  106206. */
  106207. HighlightLayer.GlowingMeshStencilReference = 0x02;
  106208. /**
  106209. * Stencil value used for the other meshes in the scene.
  106210. */
  106211. HighlightLayer.NormalMeshStencilReference = 0x01;
  106212. __decorate([
  106213. BABYLON.serialize()
  106214. ], HighlightLayer.prototype, "innerGlow", void 0);
  106215. __decorate([
  106216. BABYLON.serialize()
  106217. ], HighlightLayer.prototype, "outerGlow", void 0);
  106218. __decorate([
  106219. BABYLON.serialize()
  106220. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  106221. __decorate([
  106222. BABYLON.serialize()
  106223. ], HighlightLayer.prototype, "blurVerticalSize", null);
  106224. __decorate([
  106225. BABYLON.serialize("options")
  106226. ], HighlightLayer.prototype, "_options", void 0);
  106227. return HighlightLayer;
  106228. }(BABYLON.EffectLayer));
  106229. BABYLON.HighlightLayer = HighlightLayer;
  106230. })(BABYLON || (BABYLON = {}));
  106231. //# sourceMappingURL=babylon.highlightLayer.js.map
  106232. var BABYLON;
  106233. (function (BABYLON) {
  106234. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  106235. for (var index = 0; index < this.effectLayers.length; index++) {
  106236. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  106237. return this.effectLayers[index];
  106238. }
  106239. }
  106240. return null;
  106241. };
  106242. /**
  106243. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  106244. *
  106245. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106246. * glowy meshes to your scene.
  106247. *
  106248. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  106249. */
  106250. var GlowLayer = /** @class */ (function (_super) {
  106251. __extends(GlowLayer, _super);
  106252. /**
  106253. * Instantiates a new glow Layer and references it to the scene.
  106254. * @param name The name of the layer
  106255. * @param scene The scene to use the layer in
  106256. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  106257. */
  106258. function GlowLayer(name, scene, options) {
  106259. var _this = _super.call(this, name, scene) || this;
  106260. _this._intensity = 1.0;
  106261. _this._includedOnlyMeshes = [];
  106262. _this._excludedMeshes = [];
  106263. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  106264. // Adapt options
  106265. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  106266. // Initialize the layer
  106267. _this._init({
  106268. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  106269. camera: _this._options.camera,
  106270. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106271. mainTextureRatio: _this._options.mainTextureRatio,
  106272. renderingGroupId: _this._options.renderingGroupId
  106273. });
  106274. return _this;
  106275. }
  106276. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  106277. /**
  106278. * Gets the kernel size of the blur.
  106279. */
  106280. get: function () {
  106281. return this._horizontalBlurPostprocess1.kernel;
  106282. },
  106283. /**
  106284. * Sets the kernel size of the blur.
  106285. */
  106286. set: function (value) {
  106287. this._horizontalBlurPostprocess1.kernel = value;
  106288. this._verticalBlurPostprocess1.kernel = value;
  106289. this._horizontalBlurPostprocess2.kernel = value;
  106290. this._verticalBlurPostprocess2.kernel = value;
  106291. },
  106292. enumerable: true,
  106293. configurable: true
  106294. });
  106295. Object.defineProperty(GlowLayer.prototype, "intensity", {
  106296. /**
  106297. * Gets the glow intensity.
  106298. */
  106299. get: function () {
  106300. return this._intensity;
  106301. },
  106302. /**
  106303. * Sets the glow intensity.
  106304. */
  106305. set: function (value) {
  106306. this._intensity = value;
  106307. },
  106308. enumerable: true,
  106309. configurable: true
  106310. });
  106311. /**
  106312. * Get the effect name of the layer.
  106313. * @return The effect name
  106314. */
  106315. GlowLayer.prototype.getEffectName = function () {
  106316. return GlowLayer.EffectName;
  106317. };
  106318. /**
  106319. * Create the merge effect. This is the shader use to blit the information back
  106320. * to the main canvas at the end of the scene rendering.
  106321. */
  106322. GlowLayer.prototype._createMergeEffect = function () {
  106323. // Effect
  106324. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  106325. };
  106326. /**
  106327. * Creates the render target textures and post processes used in the glow layer.
  106328. */
  106329. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  106330. var _this = this;
  106331. var blurTextureWidth = this._mainTextureDesiredSize.width;
  106332. var blurTextureHeight = this._mainTextureDesiredSize.height;
  106333. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106334. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106335. var textureType = 0;
  106336. if (this._engine.getCaps().textureHalfFloatRender) {
  106337. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106338. }
  106339. else {
  106340. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106341. }
  106342. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  106343. width: blurTextureWidth,
  106344. height: blurTextureHeight
  106345. }, this._scene, false, true, textureType);
  106346. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106347. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106348. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106349. this._blurTexture1.renderParticles = false;
  106350. this._blurTexture1.ignoreCameraViewport = true;
  106351. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  106352. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  106353. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  106354. width: blurTextureWidth2,
  106355. height: blurTextureHeight2
  106356. }, this._scene, false, true, textureType);
  106357. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106358. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106359. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106360. this._blurTexture2.renderParticles = false;
  106361. this._blurTexture2.ignoreCameraViewport = true;
  106362. this._textures = [this._blurTexture1, this._blurTexture2];
  106363. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106364. width: blurTextureWidth,
  106365. height: blurTextureHeight
  106366. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106367. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  106368. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  106369. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  106370. effect.setTexture("textureSampler", _this._mainTexture);
  106371. });
  106372. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106373. width: blurTextureWidth,
  106374. height: blurTextureHeight
  106375. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106376. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106377. width: blurTextureWidth2,
  106378. height: blurTextureHeight2
  106379. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106380. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  106381. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  106382. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  106383. effect.setTexture("textureSampler", _this._blurTexture1);
  106384. });
  106385. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106386. width: blurTextureWidth2,
  106387. height: blurTextureHeight2
  106388. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106389. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106390. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  106391. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106392. this._mainTexture.samples = this._options.mainTextureSamples;
  106393. this._mainTexture.onAfterUnbindObservable.add(function () {
  106394. var internalTexture = _this._blurTexture1.getInternalTexture();
  106395. if (internalTexture) {
  106396. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  106397. internalTexture = _this._blurTexture2.getInternalTexture();
  106398. if (internalTexture) {
  106399. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  106400. }
  106401. }
  106402. });
  106403. // Prevent autoClear.
  106404. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106405. };
  106406. /**
  106407. * Checks for the readiness of the element composing the layer.
  106408. * @param subMesh the mesh to check for
  106409. * @param useInstances specify wether or not to use instances to render the mesh
  106410. * @param emissiveTexture the associated emissive texture used to generate the glow
  106411. * @return true if ready otherwise, false
  106412. */
  106413. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  106414. var material = subMesh.getMaterial();
  106415. var mesh = subMesh.getRenderingMesh();
  106416. if (!material || !mesh) {
  106417. return false;
  106418. }
  106419. var emissiveTexture = material.emissiveTexture;
  106420. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  106421. };
  106422. /**
  106423. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  106424. */
  106425. GlowLayer.prototype.needStencil = function () {
  106426. return false;
  106427. };
  106428. /**
  106429. * Implementation specific of rendering the generating effect on the main canvas.
  106430. * @param effect The effect used to render through
  106431. */
  106432. GlowLayer.prototype._internalRender = function (effect) {
  106433. // Texture
  106434. effect.setTexture("textureSampler", this._blurTexture1);
  106435. effect.setTexture("textureSampler2", this._blurTexture2);
  106436. effect.setFloat("offset", this._intensity);
  106437. // Cache
  106438. var engine = this._engine;
  106439. var previousStencilBuffer = engine.getStencilBuffer();
  106440. // Draw order
  106441. engine.setStencilBuffer(false);
  106442. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106443. // Draw order
  106444. engine.setStencilBuffer(previousStencilBuffer);
  106445. };
  106446. /**
  106447. * Sets the required values for both the emissive texture and and the main color.
  106448. */
  106449. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  106450. var textureLevel = 1.0;
  106451. if (this.customEmissiveTextureSelector) {
  106452. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  106453. }
  106454. else {
  106455. if (material) {
  106456. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  106457. if (this._emissiveTextureAndColor.texture) {
  106458. textureLevel = this._emissiveTextureAndColor.texture.level;
  106459. }
  106460. }
  106461. else {
  106462. this._emissiveTextureAndColor.texture = null;
  106463. }
  106464. }
  106465. if (this.customEmissiveColorSelector) {
  106466. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  106467. }
  106468. else {
  106469. if (material.emissiveColor) {
  106470. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  106471. }
  106472. else {
  106473. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  106474. }
  106475. }
  106476. };
  106477. /**
  106478. * Returns true if the mesh should render, otherwise false.
  106479. * @param mesh The mesh to render
  106480. * @returns true if it should render otherwise false
  106481. */
  106482. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  106483. return this.hasMesh(mesh);
  106484. };
  106485. /**
  106486. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  106487. * @param mesh The mesh to exclude from the glow layer
  106488. */
  106489. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  106490. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  106491. this._excludedMeshes.push(mesh.uniqueId);
  106492. }
  106493. };
  106494. /**
  106495. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  106496. * @param mesh The mesh to remove
  106497. */
  106498. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  106499. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  106500. if (index !== -1) {
  106501. this._excludedMeshes.splice(index, 1);
  106502. }
  106503. };
  106504. /**
  106505. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  106506. * @param mesh The mesh to include in the glow layer
  106507. */
  106508. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  106509. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  106510. this._includedOnlyMeshes.push(mesh.uniqueId);
  106511. }
  106512. };
  106513. /**
  106514. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  106515. * @param mesh The mesh to remove
  106516. */
  106517. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  106518. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  106519. if (index !== -1) {
  106520. this._includedOnlyMeshes.splice(index, 1);
  106521. }
  106522. };
  106523. /**
  106524. * Determine if a given mesh will be used in the glow layer
  106525. * @param mesh The mesh to test
  106526. * @returns true if the mesh will be highlighted by the current glow layer
  106527. */
  106528. GlowLayer.prototype.hasMesh = function (mesh) {
  106529. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106530. return false;
  106531. }
  106532. // Included Mesh
  106533. if (this._includedOnlyMeshes.length) {
  106534. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  106535. }
  106536. ;
  106537. // Excluded Mesh
  106538. if (this._excludedMeshes.length) {
  106539. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  106540. }
  106541. ;
  106542. return true;
  106543. };
  106544. /**
  106545. * Free any resources and references associated to a mesh.
  106546. * Internal use
  106547. * @param mesh The mesh to free.
  106548. * @hidden
  106549. */
  106550. GlowLayer.prototype._disposeMesh = function (mesh) {
  106551. this.removeIncludedOnlyMesh(mesh);
  106552. this.removeExcludedMesh(mesh);
  106553. };
  106554. /**
  106555. * Gets the class name of the effect layer
  106556. * @returns the string with the class name of the effect layer
  106557. */
  106558. GlowLayer.prototype.getClassName = function () {
  106559. return "GlowLayer";
  106560. };
  106561. /**
  106562. * Serializes this glow layer
  106563. * @returns a serialized glow layer object
  106564. */
  106565. GlowLayer.prototype.serialize = function () {
  106566. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106567. serializationObject.customType = "BABYLON.GlowLayer";
  106568. var index;
  106569. // Included meshes
  106570. serializationObject.includedMeshes = [];
  106571. if (this._includedOnlyMeshes.length) {
  106572. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  106573. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  106574. if (mesh) {
  106575. serializationObject.includedMeshes.push(mesh.id);
  106576. }
  106577. }
  106578. }
  106579. // Excluded meshes
  106580. serializationObject.excludedMeshes = [];
  106581. if (this._excludedMeshes.length) {
  106582. for (index = 0; index < this._excludedMeshes.length; index++) {
  106583. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  106584. if (mesh) {
  106585. serializationObject.excludedMeshes.push(mesh.id);
  106586. }
  106587. }
  106588. }
  106589. return serializationObject;
  106590. };
  106591. /**
  106592. * Creates a Glow Layer from parsed glow layer data
  106593. * @param parsedGlowLayer defines glow layer data
  106594. * @param scene defines the current scene
  106595. * @param rootUrl defines the root URL containing the glow layer information
  106596. * @returns a parsed Glow Layer
  106597. */
  106598. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  106599. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  106600. var index;
  106601. // Excluded meshes
  106602. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  106603. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  106604. if (mesh) {
  106605. gl.addExcludedMesh(mesh);
  106606. }
  106607. }
  106608. // Included meshes
  106609. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  106610. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  106611. if (mesh) {
  106612. gl.addIncludedOnlyMesh(mesh);
  106613. }
  106614. }
  106615. return gl;
  106616. };
  106617. /**
  106618. * Effect Name of the layer.
  106619. */
  106620. GlowLayer.EffectName = "GlowLayer";
  106621. /**
  106622. * The default blur kernel size used for the glow.
  106623. */
  106624. GlowLayer.DefaultBlurKernelSize = 32;
  106625. /**
  106626. * The default texture size ratio used for the glow.
  106627. */
  106628. GlowLayer.DefaultTextureRatio = 0.5;
  106629. __decorate([
  106630. BABYLON.serialize()
  106631. ], GlowLayer.prototype, "blurKernelSize", null);
  106632. __decorate([
  106633. BABYLON.serialize()
  106634. ], GlowLayer.prototype, "intensity", null);
  106635. __decorate([
  106636. BABYLON.serialize("options")
  106637. ], GlowLayer.prototype, "_options", void 0);
  106638. return GlowLayer;
  106639. }(BABYLON.EffectLayer));
  106640. BABYLON.GlowLayer = GlowLayer;
  106641. })(BABYLON || (BABYLON = {}));
  106642. //# sourceMappingURL=babylon.glowLayer.js.map
  106643. var BABYLON;
  106644. (function (BABYLON) {
  106645. /**
  106646. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  106647. */
  106648. var AssetTaskState;
  106649. (function (AssetTaskState) {
  106650. /**
  106651. * Initialization
  106652. */
  106653. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  106654. /**
  106655. * Running
  106656. */
  106657. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  106658. /**
  106659. * Done
  106660. */
  106661. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  106662. /**
  106663. * Error
  106664. */
  106665. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  106666. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  106667. /**
  106668. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  106669. */
  106670. var AbstractAssetTask = /** @class */ (function () {
  106671. /**
  106672. * Creates a new {BABYLON.AssetsManager}
  106673. * @param name defines the name of the task
  106674. */
  106675. function AbstractAssetTask(
  106676. /**
  106677. * Task name
  106678. */ name) {
  106679. this.name = name;
  106680. this._isCompleted = false;
  106681. this._taskState = AssetTaskState.INIT;
  106682. }
  106683. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  106684. /**
  106685. * Get if the task is completed
  106686. */
  106687. get: function () {
  106688. return this._isCompleted;
  106689. },
  106690. enumerable: true,
  106691. configurable: true
  106692. });
  106693. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  106694. /**
  106695. * Gets the current state of the task
  106696. */
  106697. get: function () {
  106698. return this._taskState;
  106699. },
  106700. enumerable: true,
  106701. configurable: true
  106702. });
  106703. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  106704. /**
  106705. * Gets the current error object (if task is in error)
  106706. */
  106707. get: function () {
  106708. return this._errorObject;
  106709. },
  106710. enumerable: true,
  106711. configurable: true
  106712. });
  106713. /**
  106714. * Internal only
  106715. * @hidden
  106716. */
  106717. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  106718. if (this._errorObject) {
  106719. return;
  106720. }
  106721. this._errorObject = {
  106722. message: message,
  106723. exception: exception
  106724. };
  106725. };
  106726. /**
  106727. * Execute the current task
  106728. * @param scene defines the scene where you want your assets to be loaded
  106729. * @param onSuccess is a callback called when the task is successfully executed
  106730. * @param onError is a callback called if an error occurs
  106731. */
  106732. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106733. var _this = this;
  106734. this._taskState = AssetTaskState.RUNNING;
  106735. this.runTask(scene, function () {
  106736. _this.onDoneCallback(onSuccess, onError);
  106737. }, function (msg, exception) {
  106738. _this.onErrorCallback(onError, msg, exception);
  106739. });
  106740. };
  106741. /**
  106742. * Execute the current task
  106743. * @param scene defines the scene where you want your assets to be loaded
  106744. * @param onSuccess is a callback called when the task is successfully executed
  106745. * @param onError is a callback called if an error occurs
  106746. */
  106747. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106748. throw new Error("runTask is not implemented");
  106749. };
  106750. /**
  106751. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  106752. * This can be used with failed tasks that have the reason for failure fixed.
  106753. */
  106754. AbstractAssetTask.prototype.reset = function () {
  106755. this._taskState = AssetTaskState.INIT;
  106756. };
  106757. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  106758. this._taskState = AssetTaskState.ERROR;
  106759. this._errorObject = {
  106760. message: message,
  106761. exception: exception
  106762. };
  106763. if (this.onError) {
  106764. this.onError(this, message, exception);
  106765. }
  106766. onError();
  106767. };
  106768. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  106769. try {
  106770. this._taskState = AssetTaskState.DONE;
  106771. this._isCompleted = true;
  106772. if (this.onSuccess) {
  106773. this.onSuccess(this);
  106774. }
  106775. onSuccess();
  106776. }
  106777. catch (e) {
  106778. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  106779. }
  106780. };
  106781. return AbstractAssetTask;
  106782. }());
  106783. BABYLON.AbstractAssetTask = AbstractAssetTask;
  106784. /**
  106785. * Class used to share progress information about assets loading
  106786. */
  106787. var AssetsProgressEvent = /** @class */ (function () {
  106788. /**
  106789. * Creates a {BABYLON.AssetsProgressEvent}
  106790. * @param remainingCount defines the number of remaining tasks to process
  106791. * @param totalCount defines the total number of tasks
  106792. * @param task defines the task that was just processed
  106793. */
  106794. function AssetsProgressEvent(remainingCount, totalCount, task) {
  106795. this.remainingCount = remainingCount;
  106796. this.totalCount = totalCount;
  106797. this.task = task;
  106798. }
  106799. return AssetsProgressEvent;
  106800. }());
  106801. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  106802. /**
  106803. * Define a task used by {BABYLON.AssetsManager} to load meshes
  106804. */
  106805. var MeshAssetTask = /** @class */ (function (_super) {
  106806. __extends(MeshAssetTask, _super);
  106807. /**
  106808. * Creates a new {BABYLON.MeshAssetTask}
  106809. * @param name defines the name of the task
  106810. * @param meshesNames defines the list of mesh's names you want to load
  106811. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  106812. * @param sceneFilename defines the filename of the scene to load from
  106813. */
  106814. function MeshAssetTask(
  106815. /**
  106816. * Defines the name of the task
  106817. */
  106818. name,
  106819. /**
  106820. * Defines the list of mesh's names you want to load
  106821. */
  106822. meshesNames,
  106823. /**
  106824. * Defines the root url to use as a base to load your meshes and associated resources
  106825. */
  106826. rootUrl,
  106827. /**
  106828. * Defines the filename of the scene to load from
  106829. */
  106830. sceneFilename) {
  106831. var _this = _super.call(this, name) || this;
  106832. _this.name = name;
  106833. _this.meshesNames = meshesNames;
  106834. _this.rootUrl = rootUrl;
  106835. _this.sceneFilename = sceneFilename;
  106836. return _this;
  106837. }
  106838. /**
  106839. * Execute the current task
  106840. * @param scene defines the scene where you want your assets to be loaded
  106841. * @param onSuccess is a callback called when the task is successfully executed
  106842. * @param onError is a callback called if an error occurs
  106843. */
  106844. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106845. var _this = this;
  106846. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  106847. _this.loadedMeshes = meshes;
  106848. _this.loadedParticleSystems = particleSystems;
  106849. _this.loadedSkeletons = skeletons;
  106850. onSuccess();
  106851. }, null, function (scene, message, exception) {
  106852. onError(message, exception);
  106853. });
  106854. };
  106855. return MeshAssetTask;
  106856. }(AbstractAssetTask));
  106857. BABYLON.MeshAssetTask = MeshAssetTask;
  106858. /**
  106859. * Define a task used by {BABYLON.AssetsManager} to load text content
  106860. */
  106861. var TextFileAssetTask = /** @class */ (function (_super) {
  106862. __extends(TextFileAssetTask, _super);
  106863. /**
  106864. * Creates a new TextFileAssetTask object
  106865. * @param name defines the name of the task
  106866. * @param url defines the location of the file to load
  106867. */
  106868. function TextFileAssetTask(
  106869. /**
  106870. * Defines the name of the task
  106871. */
  106872. name,
  106873. /**
  106874. * Defines the location of the file to load
  106875. */
  106876. url) {
  106877. var _this = _super.call(this, name) || this;
  106878. _this.name = name;
  106879. _this.url = url;
  106880. return _this;
  106881. }
  106882. /**
  106883. * Execute the current task
  106884. * @param scene defines the scene where you want your assets to be loaded
  106885. * @param onSuccess is a callback called when the task is successfully executed
  106886. * @param onError is a callback called if an error occurs
  106887. */
  106888. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106889. var _this = this;
  106890. scene._loadFile(this.url, function (data) {
  106891. _this.text = data;
  106892. onSuccess();
  106893. }, undefined, false, false, function (request, exception) {
  106894. if (request) {
  106895. onError(request.status + " " + request.statusText, exception);
  106896. }
  106897. });
  106898. };
  106899. return TextFileAssetTask;
  106900. }(AbstractAssetTask));
  106901. BABYLON.TextFileAssetTask = TextFileAssetTask;
  106902. /**
  106903. * Define a task used by {BABYLON.AssetsManager} to load binary data
  106904. */
  106905. var BinaryFileAssetTask = /** @class */ (function (_super) {
  106906. __extends(BinaryFileAssetTask, _super);
  106907. /**
  106908. * Creates a new BinaryFileAssetTask object
  106909. * @param name defines the name of the new task
  106910. * @param url defines the location of the file to load
  106911. */
  106912. function BinaryFileAssetTask(
  106913. /**
  106914. * Defines the name of the task
  106915. */
  106916. name,
  106917. /**
  106918. * Defines the location of the file to load
  106919. */
  106920. url) {
  106921. var _this = _super.call(this, name) || this;
  106922. _this.name = name;
  106923. _this.url = url;
  106924. return _this;
  106925. }
  106926. /**
  106927. * Execute the current task
  106928. * @param scene defines the scene where you want your assets to be loaded
  106929. * @param onSuccess is a callback called when the task is successfully executed
  106930. * @param onError is a callback called if an error occurs
  106931. */
  106932. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106933. var _this = this;
  106934. scene._loadFile(this.url, function (data) {
  106935. _this.data = data;
  106936. onSuccess();
  106937. }, undefined, true, true, function (request, exception) {
  106938. if (request) {
  106939. onError(request.status + " " + request.statusText, exception);
  106940. }
  106941. });
  106942. };
  106943. return BinaryFileAssetTask;
  106944. }(AbstractAssetTask));
  106945. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  106946. /**
  106947. * Define a task used by {BABYLON.AssetsManager} to load images
  106948. */
  106949. var ImageAssetTask = /** @class */ (function (_super) {
  106950. __extends(ImageAssetTask, _super);
  106951. /**
  106952. * Creates a new ImageAssetTask
  106953. * @param name defines the name of the task
  106954. * @param url defines the location of the image to load
  106955. */
  106956. function ImageAssetTask(
  106957. /**
  106958. * Defines the name of the task
  106959. */
  106960. name,
  106961. /**
  106962. * Defines the location of the image to load
  106963. */
  106964. url) {
  106965. var _this = _super.call(this, name) || this;
  106966. _this.name = name;
  106967. _this.url = url;
  106968. return _this;
  106969. }
  106970. /**
  106971. * Execute the current task
  106972. * @param scene defines the scene where you want your assets to be loaded
  106973. * @param onSuccess is a callback called when the task is successfully executed
  106974. * @param onError is a callback called if an error occurs
  106975. */
  106976. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106977. var _this = this;
  106978. var img = new Image();
  106979. BABYLON.Tools.SetCorsBehavior(this.url, img);
  106980. img.onload = function () {
  106981. _this.image = img;
  106982. onSuccess();
  106983. };
  106984. img.onerror = function (err) {
  106985. onError("Error loading image", err);
  106986. };
  106987. img.src = this.url;
  106988. };
  106989. return ImageAssetTask;
  106990. }(AbstractAssetTask));
  106991. BABYLON.ImageAssetTask = ImageAssetTask;
  106992. /**
  106993. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  106994. */
  106995. var TextureAssetTask = /** @class */ (function (_super) {
  106996. __extends(TextureAssetTask, _super);
  106997. /**
  106998. * Creates a new TextureAssetTask object
  106999. * @param name defines the name of the task
  107000. * @param url defines the location of the file to load
  107001. * @param noMipmap defines if mipmap should not be generated (default is false)
  107002. * @param invertY defines if texture must be inverted on Y axis (default is false)
  107003. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107004. */
  107005. function TextureAssetTask(
  107006. /**
  107007. * Defines the name of the task
  107008. */
  107009. name,
  107010. /**
  107011. * Defines the location of the file to load
  107012. */
  107013. url,
  107014. /**
  107015. * Defines if mipmap should not be generated (default is false)
  107016. */
  107017. noMipmap,
  107018. /**
  107019. * Defines if texture must be inverted on Y axis (default is false)
  107020. */
  107021. invertY,
  107022. /**
  107023. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107024. */
  107025. samplingMode) {
  107026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107027. var _this = _super.call(this, name) || this;
  107028. _this.name = name;
  107029. _this.url = url;
  107030. _this.noMipmap = noMipmap;
  107031. _this.invertY = invertY;
  107032. _this.samplingMode = samplingMode;
  107033. return _this;
  107034. }
  107035. /**
  107036. * Execute the current task
  107037. * @param scene defines the scene where you want your assets to be loaded
  107038. * @param onSuccess is a callback called when the task is successfully executed
  107039. * @param onError is a callback called if an error occurs
  107040. */
  107041. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107042. var onload = function () {
  107043. onSuccess();
  107044. };
  107045. var onerror = function (message, exception) {
  107046. onError(message, exception);
  107047. };
  107048. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  107049. };
  107050. return TextureAssetTask;
  107051. }(AbstractAssetTask));
  107052. BABYLON.TextureAssetTask = TextureAssetTask;
  107053. /**
  107054. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  107055. */
  107056. var CubeTextureAssetTask = /** @class */ (function (_super) {
  107057. __extends(CubeTextureAssetTask, _super);
  107058. /**
  107059. * Creates a new CubeTextureAssetTask
  107060. * @param name defines the name of the task
  107061. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107062. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107063. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107064. * @param files defines the explicit list of files (undefined by default)
  107065. */
  107066. function CubeTextureAssetTask(
  107067. /**
  107068. * Defines the name of the task
  107069. */
  107070. name,
  107071. /**
  107072. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107073. */
  107074. url,
  107075. /**
  107076. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107077. */
  107078. extensions,
  107079. /**
  107080. * Defines if mipmaps should not be generated (default is false)
  107081. */
  107082. noMipmap,
  107083. /**
  107084. * Defines the explicit list of files (undefined by default)
  107085. */
  107086. files) {
  107087. var _this = _super.call(this, name) || this;
  107088. _this.name = name;
  107089. _this.url = url;
  107090. _this.extensions = extensions;
  107091. _this.noMipmap = noMipmap;
  107092. _this.files = files;
  107093. return _this;
  107094. }
  107095. /**
  107096. * Execute the current task
  107097. * @param scene defines the scene where you want your assets to be loaded
  107098. * @param onSuccess is a callback called when the task is successfully executed
  107099. * @param onError is a callback called if an error occurs
  107100. */
  107101. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107102. var onload = function () {
  107103. onSuccess();
  107104. };
  107105. var onerror = function (message, exception) {
  107106. onError(message, exception);
  107107. };
  107108. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  107109. };
  107110. return CubeTextureAssetTask;
  107111. }(AbstractAssetTask));
  107112. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  107113. /**
  107114. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  107115. */
  107116. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  107117. __extends(HDRCubeTextureAssetTask, _super);
  107118. /**
  107119. * Creates a new HDRCubeTextureAssetTask object
  107120. * @param name defines the name of the task
  107121. * @param url defines the location of the file to load
  107122. * @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.
  107123. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107124. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107125. * @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)
  107126. * @param reserved Internal use only
  107127. */
  107128. function HDRCubeTextureAssetTask(
  107129. /**
  107130. * Defines the name of the task
  107131. */
  107132. name,
  107133. /**
  107134. * Defines the location of the file to load
  107135. */
  107136. url,
  107137. /**
  107138. * Defines the desired size (the more it increases the longer the generation will be)
  107139. */
  107140. size,
  107141. /**
  107142. * Defines if mipmaps should not be generated (default is false)
  107143. */
  107144. noMipmap,
  107145. /**
  107146. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107147. */
  107148. generateHarmonics,
  107149. /**
  107150. * 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)
  107151. */
  107152. gammaSpace,
  107153. /**
  107154. * Internal Use Only
  107155. */
  107156. reserved) {
  107157. if (noMipmap === void 0) { noMipmap = false; }
  107158. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107159. if (gammaSpace === void 0) { gammaSpace = false; }
  107160. if (reserved === void 0) { reserved = false; }
  107161. var _this = _super.call(this, name) || this;
  107162. _this.name = name;
  107163. _this.url = url;
  107164. _this.size = size;
  107165. _this.noMipmap = noMipmap;
  107166. _this.generateHarmonics = generateHarmonics;
  107167. _this.gammaSpace = gammaSpace;
  107168. _this.reserved = reserved;
  107169. return _this;
  107170. }
  107171. /**
  107172. * Execute the current task
  107173. * @param scene defines the scene where you want your assets to be loaded
  107174. * @param onSuccess is a callback called when the task is successfully executed
  107175. * @param onError is a callback called if an error occurs
  107176. */
  107177. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107178. var onload = function () {
  107179. onSuccess();
  107180. };
  107181. var onerror = function (message, exception) {
  107182. onError(message, exception);
  107183. };
  107184. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  107185. };
  107186. return HDRCubeTextureAssetTask;
  107187. }(AbstractAssetTask));
  107188. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  107189. /**
  107190. * This class can be used to easily import assets into a scene
  107191. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  107192. */
  107193. var AssetsManager = /** @class */ (function () {
  107194. /**
  107195. * Creates a new AssetsManager
  107196. * @param scene defines the scene to work on
  107197. */
  107198. function AssetsManager(scene) {
  107199. this._isLoading = false;
  107200. this._tasks = new Array();
  107201. this._waitingTasksCount = 0;
  107202. this._totalTasksCount = 0;
  107203. /**
  107204. * Observable called when all tasks are processed
  107205. */
  107206. this.onTaskSuccessObservable = new BABYLON.Observable();
  107207. /**
  107208. * Observable called when a task had an error
  107209. */
  107210. this.onTaskErrorObservable = new BABYLON.Observable();
  107211. /**
  107212. * Observable called when a task is successful
  107213. */
  107214. this.onTasksDoneObservable = new BABYLON.Observable();
  107215. /**
  107216. * Observable called when a task is done (whatever the result is)
  107217. */
  107218. this.onProgressObservable = new BABYLON.Observable();
  107219. /**
  107220. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  107221. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  107222. */
  107223. this.useDefaultLoadingScreen = true;
  107224. this._scene = scene;
  107225. }
  107226. /**
  107227. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  107228. * @param taskName defines the name of the new task
  107229. * @param meshesNames defines the name of meshes to load
  107230. * @param rootUrl defines the root url to use to locate files
  107231. * @param sceneFilename defines the filename of the scene file
  107232. * @returns a new {BABYLON.MeshAssetTask} object
  107233. */
  107234. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  107235. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  107236. this._tasks.push(task);
  107237. return task;
  107238. };
  107239. /**
  107240. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  107241. * @param taskName defines the name of the new task
  107242. * @param url defines the url of the file to load
  107243. * @returns a new {BABYLON.TextFileAssetTask} object
  107244. */
  107245. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  107246. var task = new TextFileAssetTask(taskName, url);
  107247. this._tasks.push(task);
  107248. return task;
  107249. };
  107250. /**
  107251. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  107252. * @param taskName defines the name of the new task
  107253. * @param url defines the url of the file to load
  107254. * @returns a new {BABYLON.BinaryFileAssetTask} object
  107255. */
  107256. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  107257. var task = new BinaryFileAssetTask(taskName, url);
  107258. this._tasks.push(task);
  107259. return task;
  107260. };
  107261. /**
  107262. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  107263. * @param taskName defines the name of the new task
  107264. * @param url defines the url of the file to load
  107265. * @returns a new {BABYLON.ImageAssetTask} object
  107266. */
  107267. AssetsManager.prototype.addImageTask = function (taskName, url) {
  107268. var task = new ImageAssetTask(taskName, url);
  107269. this._tasks.push(task);
  107270. return task;
  107271. };
  107272. /**
  107273. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  107274. * @param taskName defines the name of the new task
  107275. * @param url defines the url of the file to load
  107276. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107277. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  107278. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  107279. * @returns a new {BABYLON.TextureAssetTask} object
  107280. */
  107281. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  107282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107283. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  107284. this._tasks.push(task);
  107285. return task;
  107286. };
  107287. /**
  107288. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  107289. * @param taskName defines the name of the new task
  107290. * @param url defines the url of the file to load
  107291. * @param extensions defines the extension to use to load the cube map (can be null)
  107292. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107293. * @param files defines the list of files to load (can be null)
  107294. * @returns a new {BABYLON.CubeTextureAssetTask} object
  107295. */
  107296. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  107297. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  107298. this._tasks.push(task);
  107299. return task;
  107300. };
  107301. /**
  107302. *
  107303. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  107304. * @param taskName defines the name of the new task
  107305. * @param url defines the url of the file to load
  107306. * @param size defines the size you want for the cubemap (can be null)
  107307. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107308. * @param generateHarmonics defines if you want to automatically generate (true by default)
  107309. * @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)
  107310. * @param reserved Internal use only
  107311. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  107312. */
  107313. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  107314. if (noMipmap === void 0) { noMipmap = false; }
  107315. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107316. if (gammaSpace === void 0) { gammaSpace = false; }
  107317. if (reserved === void 0) { reserved = false; }
  107318. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  107319. this._tasks.push(task);
  107320. return task;
  107321. };
  107322. /**
  107323. * Remove a task from the assets manager.
  107324. * @param task the task to remove
  107325. */
  107326. AssetsManager.prototype.removeTask = function (task) {
  107327. var index = this._tasks.indexOf(task);
  107328. if (index > -1) {
  107329. this._tasks.splice(index, 1);
  107330. }
  107331. };
  107332. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  107333. this._waitingTasksCount--;
  107334. try {
  107335. if (this.onProgress) {
  107336. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  107337. }
  107338. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  107339. }
  107340. catch (e) {
  107341. BABYLON.Tools.Error("Error running progress callbacks.");
  107342. console.log(e);
  107343. }
  107344. if (this._waitingTasksCount === 0) {
  107345. try {
  107346. if (this.onFinish) {
  107347. this.onFinish(this._tasks);
  107348. }
  107349. // Let's remove successfull tasks
  107350. var currentTasks = this._tasks.slice();
  107351. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  107352. var task = currentTasks_1[_i];
  107353. if (task.taskState === AssetTaskState.DONE) {
  107354. var index = this._tasks.indexOf(task);
  107355. if (index > -1) {
  107356. this._tasks.splice(index, 1);
  107357. }
  107358. }
  107359. }
  107360. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107361. }
  107362. catch (e) {
  107363. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  107364. console.log(e);
  107365. }
  107366. this._isLoading = false;
  107367. this._scene.getEngine().hideLoadingUI();
  107368. }
  107369. };
  107370. AssetsManager.prototype._runTask = function (task) {
  107371. var _this = this;
  107372. var done = function () {
  107373. try {
  107374. if (_this.onTaskSuccess) {
  107375. _this.onTaskSuccess(task);
  107376. }
  107377. _this.onTaskSuccessObservable.notifyObservers(task);
  107378. _this._decreaseWaitingTasksCount(task);
  107379. }
  107380. catch (e) {
  107381. error("Error executing task success callbacks", e);
  107382. }
  107383. };
  107384. var error = function (message, exception) {
  107385. task._setErrorObject(message, exception);
  107386. if (_this.onTaskError) {
  107387. _this.onTaskError(task);
  107388. }
  107389. _this.onTaskErrorObservable.notifyObservers(task);
  107390. _this._decreaseWaitingTasksCount(task);
  107391. };
  107392. task.run(this._scene, done, error);
  107393. };
  107394. /**
  107395. * Reset the {BABYLON.AssetsManager} and remove all tasks
  107396. * @return the current instance of the {BABYLON.AssetsManager}
  107397. */
  107398. AssetsManager.prototype.reset = function () {
  107399. this._isLoading = false;
  107400. this._tasks = new Array();
  107401. return this;
  107402. };
  107403. /**
  107404. * Start the loading process
  107405. * @return the current instance of the {BABYLON.AssetsManager}
  107406. */
  107407. AssetsManager.prototype.load = function () {
  107408. if (this._isLoading) {
  107409. return this;
  107410. }
  107411. this._isLoading = true;
  107412. this._waitingTasksCount = this._tasks.length;
  107413. this._totalTasksCount = this._tasks.length;
  107414. if (this._waitingTasksCount === 0) {
  107415. this._isLoading = false;
  107416. if (this.onFinish) {
  107417. this.onFinish(this._tasks);
  107418. }
  107419. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107420. return this;
  107421. }
  107422. if (this.useDefaultLoadingScreen) {
  107423. this._scene.getEngine().displayLoadingUI();
  107424. }
  107425. for (var index = 0; index < this._tasks.length; index++) {
  107426. var task = this._tasks[index];
  107427. if (task.taskState === AssetTaskState.INIT) {
  107428. this._runTask(task);
  107429. }
  107430. }
  107431. return this;
  107432. };
  107433. return AssetsManager;
  107434. }());
  107435. BABYLON.AssetsManager = AssetsManager;
  107436. })(BABYLON || (BABYLON = {}));
  107437. //# sourceMappingURL=babylon.assetsManager.js.map
  107438. var BABYLON;
  107439. (function (BABYLON) {
  107440. var serializedGeometries = [];
  107441. var serializeGeometry = function (geometry, serializationGeometries) {
  107442. if (serializedGeometries[geometry.id]) {
  107443. return;
  107444. }
  107445. if (geometry.doNotSerialize) {
  107446. return;
  107447. }
  107448. if (geometry instanceof BABYLON.BoxGeometry) {
  107449. serializationGeometries.boxes.push(geometry.serialize());
  107450. }
  107451. else if (geometry instanceof BABYLON.SphereGeometry) {
  107452. serializationGeometries.spheres.push(geometry.serialize());
  107453. }
  107454. else if (geometry instanceof BABYLON.CylinderGeometry) {
  107455. serializationGeometries.cylinders.push(geometry.serialize());
  107456. }
  107457. else if (geometry instanceof BABYLON.TorusGeometry) {
  107458. serializationGeometries.toruses.push(geometry.serialize());
  107459. }
  107460. else if (geometry instanceof BABYLON.GroundGeometry) {
  107461. serializationGeometries.grounds.push(geometry.serialize());
  107462. }
  107463. else if (geometry instanceof BABYLON.Plane) {
  107464. serializationGeometries.planes.push(geometry.serialize());
  107465. }
  107466. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  107467. serializationGeometries.torusKnots.push(geometry.serialize());
  107468. }
  107469. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  107470. throw new Error("Unknown primitive type");
  107471. }
  107472. else {
  107473. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  107474. }
  107475. serializedGeometries[geometry.id] = true;
  107476. };
  107477. var serializeMesh = function (mesh, serializationScene) {
  107478. var serializationObject = {};
  107479. // Geometry
  107480. var geometry = mesh._geometry;
  107481. if (geometry) {
  107482. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  107483. // 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
  107484. serializeGeometry(geometry, serializationScene.geometries);
  107485. }
  107486. }
  107487. // Custom
  107488. if (mesh.serialize) {
  107489. mesh.serialize(serializationObject);
  107490. }
  107491. return serializationObject;
  107492. };
  107493. var finalizeSingleMesh = function (mesh, serializationObject) {
  107494. //only works if the mesh is already loaded
  107495. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107496. //serialize material
  107497. if (mesh.material) {
  107498. if (mesh.material instanceof BABYLON.MultiMaterial) {
  107499. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  107500. serializationObject.materials = serializationObject.materials || [];
  107501. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107502. serializationObject.multiMaterials.push(mesh.material.serialize());
  107503. var _loop_1 = function (submaterial) {
  107504. if (submaterial) {
  107505. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  107506. serializationObject.materials.push(submaterial.serialize());
  107507. }
  107508. }
  107509. };
  107510. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  107511. var submaterial = _a[_i];
  107512. _loop_1(submaterial);
  107513. }
  107514. }
  107515. }
  107516. else {
  107517. serializationObject.materials = serializationObject.materials || [];
  107518. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107519. serializationObject.materials.push(mesh.material.serialize());
  107520. }
  107521. }
  107522. }
  107523. //serialize geometry
  107524. var geometry = mesh._geometry;
  107525. if (geometry) {
  107526. if (!serializationObject.geometries) {
  107527. serializationObject.geometries = {};
  107528. serializationObject.geometries.boxes = [];
  107529. serializationObject.geometries.spheres = [];
  107530. serializationObject.geometries.cylinders = [];
  107531. serializationObject.geometries.toruses = [];
  107532. serializationObject.geometries.grounds = [];
  107533. serializationObject.geometries.planes = [];
  107534. serializationObject.geometries.torusKnots = [];
  107535. serializationObject.geometries.vertexData = [];
  107536. }
  107537. serializeGeometry(geometry, serializationObject.geometries);
  107538. }
  107539. // Skeletons
  107540. if (mesh.skeleton) {
  107541. serializationObject.skeletons = serializationObject.skeletons || [];
  107542. serializationObject.skeletons.push(mesh.skeleton.serialize());
  107543. }
  107544. //serialize the actual mesh
  107545. serializationObject.meshes = serializationObject.meshes || [];
  107546. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107547. }
  107548. };
  107549. var SceneSerializer = /** @class */ (function () {
  107550. function SceneSerializer() {
  107551. }
  107552. SceneSerializer.ClearCache = function () {
  107553. serializedGeometries = [];
  107554. };
  107555. SceneSerializer.Serialize = function (scene) {
  107556. var serializationObject = {};
  107557. SceneSerializer.ClearCache();
  107558. // Scene
  107559. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  107560. serializationObject.autoClear = scene.autoClear;
  107561. serializationObject.clearColor = scene.clearColor.asArray();
  107562. serializationObject.ambientColor = scene.ambientColor.asArray();
  107563. serializationObject.gravity = scene.gravity.asArray();
  107564. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  107565. serializationObject.workerCollisions = scene.workerCollisions;
  107566. // Fog
  107567. if (scene.fogMode && scene.fogMode !== 0) {
  107568. serializationObject.fogMode = scene.fogMode;
  107569. serializationObject.fogColor = scene.fogColor.asArray();
  107570. serializationObject.fogStart = scene.fogStart;
  107571. serializationObject.fogEnd = scene.fogEnd;
  107572. serializationObject.fogDensity = scene.fogDensity;
  107573. }
  107574. //Physics
  107575. if (scene.isPhysicsEnabled()) {
  107576. var physicEngine = scene.getPhysicsEngine();
  107577. if (physicEngine) {
  107578. serializationObject.physicsEnabled = true;
  107579. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  107580. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  107581. }
  107582. }
  107583. // Metadata
  107584. if (scene.metadata) {
  107585. serializationObject.metadata = scene.metadata;
  107586. }
  107587. // Morph targets
  107588. serializationObject.morphTargetManagers = [];
  107589. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  107590. var abstractMesh = _a[_i];
  107591. var manager = abstractMesh.morphTargetManager;
  107592. if (manager) {
  107593. serializationObject.morphTargetManagers.push(manager.serialize());
  107594. }
  107595. }
  107596. // Lights
  107597. serializationObject.lights = [];
  107598. var index;
  107599. var light;
  107600. for (index = 0; index < scene.lights.length; index++) {
  107601. light = scene.lights[index];
  107602. if (!light.doNotSerialize) {
  107603. serializationObject.lights.push(light.serialize());
  107604. }
  107605. }
  107606. // Cameras
  107607. serializationObject.cameras = [];
  107608. for (index = 0; index < scene.cameras.length; index++) {
  107609. var camera = scene.cameras[index];
  107610. if (!camera.doNotSerialize) {
  107611. serializationObject.cameras.push(camera.serialize());
  107612. }
  107613. }
  107614. if (scene.activeCamera) {
  107615. serializationObject.activeCameraID = scene.activeCamera.id;
  107616. }
  107617. // Animations
  107618. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  107619. // Materials
  107620. serializationObject.materials = [];
  107621. serializationObject.multiMaterials = [];
  107622. var material;
  107623. for (index = 0; index < scene.materials.length; index++) {
  107624. material = scene.materials[index];
  107625. if (!material.doNotSerialize) {
  107626. serializationObject.materials.push(material.serialize());
  107627. }
  107628. }
  107629. // MultiMaterials
  107630. serializationObject.multiMaterials = [];
  107631. for (index = 0; index < scene.multiMaterials.length; index++) {
  107632. var multiMaterial = scene.multiMaterials[index];
  107633. serializationObject.multiMaterials.push(multiMaterial.serialize());
  107634. }
  107635. // Environment texture
  107636. if (scene.environmentTexture) {
  107637. serializationObject.environmentTexture = scene.environmentTexture.name;
  107638. }
  107639. // Skeletons
  107640. serializationObject.skeletons = [];
  107641. for (index = 0; index < scene.skeletons.length; index++) {
  107642. var skeleton = scene.skeletons[index];
  107643. if (!skeleton.doNotSerialize) {
  107644. serializationObject.skeletons.push(skeleton.serialize());
  107645. }
  107646. }
  107647. // Transform nodes
  107648. serializationObject.transformNodes = [];
  107649. for (index = 0; index < scene.transformNodes.length; index++) {
  107650. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  107651. }
  107652. // Geometries
  107653. serializationObject.geometries = {};
  107654. serializationObject.geometries.boxes = [];
  107655. serializationObject.geometries.spheres = [];
  107656. serializationObject.geometries.cylinders = [];
  107657. serializationObject.geometries.toruses = [];
  107658. serializationObject.geometries.grounds = [];
  107659. serializationObject.geometries.planes = [];
  107660. serializationObject.geometries.torusKnots = [];
  107661. serializationObject.geometries.vertexData = [];
  107662. serializedGeometries = [];
  107663. var geometries = scene.getGeometries();
  107664. for (index = 0; index < geometries.length; index++) {
  107665. var geometry = geometries[index];
  107666. if (geometry.isReady()) {
  107667. serializeGeometry(geometry, serializationObject.geometries);
  107668. }
  107669. }
  107670. // Meshes
  107671. serializationObject.meshes = [];
  107672. for (index = 0; index < scene.meshes.length; index++) {
  107673. var abstractMesh = scene.meshes[index];
  107674. if (abstractMesh instanceof BABYLON.Mesh) {
  107675. var mesh = abstractMesh;
  107676. if (!mesh.doNotSerialize) {
  107677. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107678. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107679. }
  107680. }
  107681. }
  107682. }
  107683. // Particles Systems
  107684. serializationObject.particleSystems = [];
  107685. for (index = 0; index < scene.particleSystems.length; index++) {
  107686. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  107687. }
  107688. // Action Manager
  107689. if (scene.actionManager) {
  107690. serializationObject.actions = scene.actionManager.serialize("scene");
  107691. }
  107692. // Components
  107693. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  107694. var component = _c[_b];
  107695. component.serialize(serializationObject);
  107696. }
  107697. return serializationObject;
  107698. };
  107699. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  107700. if (withParents === void 0) { withParents = false; }
  107701. if (withChildren === void 0) { withChildren = false; }
  107702. var serializationObject = {};
  107703. SceneSerializer.ClearCache();
  107704. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  107705. if (withParents || withChildren) {
  107706. //deliberate for loop! not for each, appended should be processed as well.
  107707. for (var i = 0; i < toSerialize.length; ++i) {
  107708. if (withChildren) {
  107709. toSerialize[i].getDescendants().forEach(function (node) {
  107710. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  107711. toSerialize.push(node);
  107712. }
  107713. });
  107714. }
  107715. //make sure the array doesn't contain the object already
  107716. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  107717. toSerialize.push(toSerialize[i].parent);
  107718. }
  107719. }
  107720. }
  107721. toSerialize.forEach(function (mesh) {
  107722. finalizeSingleMesh(mesh, serializationObject);
  107723. });
  107724. return serializationObject;
  107725. };
  107726. return SceneSerializer;
  107727. }());
  107728. BABYLON.SceneSerializer = SceneSerializer;
  107729. })(BABYLON || (BABYLON = {}));
  107730. //# sourceMappingURL=babylon.sceneSerializer.js.map
  107731. var BABYLON;
  107732. (function (BABYLON) {
  107733. /**
  107734. * Class used to generate realtime reflection / refraction cube textures
  107735. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  107736. */
  107737. var ReflectionProbe = /** @class */ (function () {
  107738. /**
  107739. * Creates a new reflection probe
  107740. * @param name defines the name of the probe
  107741. * @param size defines the texture resolution (for each face)
  107742. * @param scene defines the hosting scene
  107743. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  107744. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  107745. */
  107746. function ReflectionProbe(
  107747. /** defines the name of the probe */
  107748. name, size, scene, generateMipMaps, useFloat) {
  107749. if (generateMipMaps === void 0) { generateMipMaps = true; }
  107750. if (useFloat === void 0) { useFloat = false; }
  107751. var _this = this;
  107752. this.name = name;
  107753. this._viewMatrix = BABYLON.Matrix.Identity();
  107754. this._target = BABYLON.Vector3.Zero();
  107755. this._add = BABYLON.Vector3.Zero();
  107756. this._invertYAxis = false;
  107757. /** Gets or sets probe position (center of the cube map) */
  107758. this.position = BABYLON.Vector3.Zero();
  107759. this._scene = scene;
  107760. // Create the scene field if not exist.
  107761. if (!this._scene.reflectionProbes) {
  107762. this._scene.reflectionProbes = new Array();
  107763. }
  107764. this._scene.reflectionProbes.push(this);
  107765. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  107766. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  107767. switch (faceIndex) {
  107768. case 0:
  107769. _this._add.copyFromFloats(1, 0, 0);
  107770. break;
  107771. case 1:
  107772. _this._add.copyFromFloats(-1, 0, 0);
  107773. break;
  107774. case 2:
  107775. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  107776. break;
  107777. case 3:
  107778. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  107779. break;
  107780. case 4:
  107781. _this._add.copyFromFloats(0, 0, 1);
  107782. break;
  107783. case 5:
  107784. _this._add.copyFromFloats(0, 0, -1);
  107785. break;
  107786. }
  107787. if (_this._attachedMesh) {
  107788. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  107789. }
  107790. _this.position.addToRef(_this._add, _this._target);
  107791. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  107792. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  107793. scene._forcedViewPosition = _this.position;
  107794. });
  107795. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  107796. scene._forcedViewPosition = null;
  107797. scene.updateTransformMatrix(true);
  107798. });
  107799. if (scene.activeCamera) {
  107800. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  107801. }
  107802. }
  107803. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  107804. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  107805. get: function () {
  107806. return this._renderTargetTexture.samples;
  107807. },
  107808. set: function (value) {
  107809. this._renderTargetTexture.samples = value;
  107810. },
  107811. enumerable: true,
  107812. configurable: true
  107813. });
  107814. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  107815. /** Gets or sets the refresh rate to use (on every frame by default) */
  107816. get: function () {
  107817. return this._renderTargetTexture.refreshRate;
  107818. },
  107819. set: function (value) {
  107820. this._renderTargetTexture.refreshRate = value;
  107821. },
  107822. enumerable: true,
  107823. configurable: true
  107824. });
  107825. /**
  107826. * Gets the hosting scene
  107827. * @returns a Scene
  107828. */
  107829. ReflectionProbe.prototype.getScene = function () {
  107830. return this._scene;
  107831. };
  107832. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  107833. /** Gets the internal CubeTexture used to render to */
  107834. get: function () {
  107835. return this._renderTargetTexture;
  107836. },
  107837. enumerable: true,
  107838. configurable: true
  107839. });
  107840. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  107841. /** Gets the list of meshes to render */
  107842. get: function () {
  107843. return this._renderTargetTexture.renderList;
  107844. },
  107845. enumerable: true,
  107846. configurable: true
  107847. });
  107848. /**
  107849. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  107850. * @param mesh defines the mesh to attach to
  107851. */
  107852. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  107853. this._attachedMesh = mesh;
  107854. };
  107855. /**
  107856. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  107857. * @param renderingGroupId The rendering group id corresponding to its index
  107858. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  107859. */
  107860. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  107861. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  107862. };
  107863. /**
  107864. * Clean all associated resources
  107865. */
  107866. ReflectionProbe.prototype.dispose = function () {
  107867. var index = this._scene.reflectionProbes.indexOf(this);
  107868. if (index !== -1) {
  107869. // Remove from the scene if found
  107870. this._scene.reflectionProbes.splice(index, 1);
  107871. }
  107872. if (this._renderTargetTexture) {
  107873. this._renderTargetTexture.dispose();
  107874. this._renderTargetTexture = null;
  107875. }
  107876. };
  107877. return ReflectionProbe;
  107878. }());
  107879. BABYLON.ReflectionProbe = ReflectionProbe;
  107880. })(BABYLON || (BABYLON = {}));
  107881. //# sourceMappingURL=babylon.reflectionProbe.js.map
  107882. var BABYLON;
  107883. (function (BABYLON) {
  107884. /**
  107885. * Defines the layer scene component responsible to manage any layers
  107886. * in a given scene.
  107887. */
  107888. var LayerSceneComponent = /** @class */ (function () {
  107889. /**
  107890. * Creates a new instance of the component for the given scene
  107891. * @param scene Defines the scene to register the component in
  107892. */
  107893. function LayerSceneComponent(scene) {
  107894. /**
  107895. * The component name helpfull to identify the component in the list of scene components.
  107896. */
  107897. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  107898. this.scene = scene;
  107899. this._engine = scene.getEngine();
  107900. scene.layers = new Array();
  107901. }
  107902. /**
  107903. * Registers the component in a given scene
  107904. */
  107905. LayerSceneComponent.prototype.register = function () {
  107906. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  107907. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  107908. };
  107909. /**
  107910. * Rebuilds the elements related to this component in case of
  107911. * context lost for instance.
  107912. */
  107913. LayerSceneComponent.prototype.rebuild = function () {
  107914. var layers = this.scene.layers;
  107915. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107916. var layer = layers_1[_i];
  107917. layer._rebuild();
  107918. }
  107919. };
  107920. /**
  107921. * Disposes the component and the associated ressources.
  107922. */
  107923. LayerSceneComponent.prototype.dispose = function () {
  107924. var layers = this.scene.layers;
  107925. while (layers.length) {
  107926. layers[0].dispose();
  107927. }
  107928. };
  107929. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  107930. var layers = this.scene.layers;
  107931. if (layers.length) {
  107932. this._engine.setDepthBuffer(false);
  107933. var cameraLayerMask = camera.layerMask;
  107934. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107935. var layer = layers_2[_i];
  107936. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  107937. layer.render();
  107938. }
  107939. }
  107940. this._engine.setDepthBuffer(true);
  107941. }
  107942. };
  107943. LayerSceneComponent.prototype._drawBackground = function (camera) {
  107944. this._draw(camera, true);
  107945. };
  107946. LayerSceneComponent.prototype._drawForeground = function (camera) {
  107947. this._draw(camera, false);
  107948. };
  107949. return LayerSceneComponent;
  107950. }());
  107951. BABYLON.LayerSceneComponent = LayerSceneComponent;
  107952. })(BABYLON || (BABYLON = {}));
  107953. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  107954. var BABYLON;
  107955. (function (BABYLON) {
  107956. /**
  107957. * This represents a full screen 2d layer.
  107958. * This can be usefull to display a picture in the background of your scene for instance.
  107959. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107960. */
  107961. var Layer = /** @class */ (function () {
  107962. /**
  107963. * Instantiates a new layer.
  107964. * This represents a full screen 2d layer.
  107965. * This can be usefull to display a picture in the background of your scene for instance.
  107966. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107967. * @param name Define the name of the layer in the scene
  107968. * @param imgUrl Define the url of the texture to display in the layer
  107969. * @param scene Define the scene the layer belongs to
  107970. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  107971. * @param color Defines a color for the layer
  107972. */
  107973. function Layer(
  107974. /**
  107975. * Define the name of the layer.
  107976. */
  107977. name, imgUrl, scene, isBackground, color) {
  107978. this.name = name;
  107979. /**
  107980. * Define the scale of the layer in order to zoom in out of the texture.
  107981. */
  107982. this.scale = new BABYLON.Vector2(1, 1);
  107983. /**
  107984. * Define an offset for the layer in order to shift the texture.
  107985. */
  107986. this.offset = new BABYLON.Vector2(0, 0);
  107987. /**
  107988. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  107989. */
  107990. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  107991. /**
  107992. * Define a mask to restrict the layer to only some of the scene cameras.
  107993. */
  107994. this.layerMask = 0x0FFFFFFF;
  107995. this._vertexBuffers = {};
  107996. /**
  107997. * An event triggered when the layer is disposed.
  107998. */
  107999. this.onDisposeObservable = new BABYLON.Observable();
  108000. /**
  108001. * An event triggered before rendering the scene
  108002. */
  108003. this.onBeforeRenderObservable = new BABYLON.Observable();
  108004. /**
  108005. * An event triggered after rendering the scene
  108006. */
  108007. this.onAfterRenderObservable = new BABYLON.Observable();
  108008. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  108009. this.isBackground = isBackground === undefined ? true : isBackground;
  108010. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  108011. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  108012. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  108013. if (!layerComponent) {
  108014. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  108015. this._scene._addComponent(layerComponent);
  108016. }
  108017. this._scene.layers.push(this);
  108018. var engine = this._scene.getEngine();
  108019. // VBO
  108020. var vertices = [];
  108021. vertices.push(1, 1);
  108022. vertices.push(-1, 1);
  108023. vertices.push(-1, -1);
  108024. vertices.push(1, -1);
  108025. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108026. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108027. this._createIndexBuffer();
  108028. // Effects
  108029. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  108030. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  108031. }
  108032. Object.defineProperty(Layer.prototype, "onDispose", {
  108033. /**
  108034. * Back compatibility with callback before the onDisposeObservable existed.
  108035. * The set callback will be triggered when the layer has been disposed.
  108036. */
  108037. set: function (callback) {
  108038. if (this._onDisposeObserver) {
  108039. this.onDisposeObservable.remove(this._onDisposeObserver);
  108040. }
  108041. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  108042. },
  108043. enumerable: true,
  108044. configurable: true
  108045. });
  108046. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  108047. /**
  108048. * Back compatibility with callback before the onBeforeRenderObservable existed.
  108049. * The set callback will be triggered just before rendering the layer.
  108050. */
  108051. set: function (callback) {
  108052. if (this._onBeforeRenderObserver) {
  108053. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  108054. }
  108055. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  108056. },
  108057. enumerable: true,
  108058. configurable: true
  108059. });
  108060. Object.defineProperty(Layer.prototype, "onAfterRender", {
  108061. /**
  108062. * Back compatibility with callback before the onAfterRenderObservable existed.
  108063. * The set callback will be triggered just after rendering the layer.
  108064. */
  108065. set: function (callback) {
  108066. if (this._onAfterRenderObserver) {
  108067. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  108068. }
  108069. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  108070. },
  108071. enumerable: true,
  108072. configurable: true
  108073. });
  108074. Layer.prototype._createIndexBuffer = function () {
  108075. var engine = this._scene.getEngine();
  108076. // Indices
  108077. var indices = [];
  108078. indices.push(0);
  108079. indices.push(1);
  108080. indices.push(2);
  108081. indices.push(0);
  108082. indices.push(2);
  108083. indices.push(3);
  108084. this._indexBuffer = engine.createIndexBuffer(indices);
  108085. };
  108086. /** @hidden */
  108087. Layer.prototype._rebuild = function () {
  108088. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108089. if (vb) {
  108090. vb._rebuild();
  108091. }
  108092. this._createIndexBuffer();
  108093. };
  108094. /**
  108095. * Renders the layer in the scene.
  108096. */
  108097. Layer.prototype.render = function () {
  108098. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  108099. // Check
  108100. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  108101. return;
  108102. var engine = this._scene.getEngine();
  108103. this.onBeforeRenderObservable.notifyObservers(this);
  108104. // Render
  108105. engine.enableEffect(currentEffect);
  108106. engine.setState(false);
  108107. // Texture
  108108. currentEffect.setTexture("textureSampler", this.texture);
  108109. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  108110. // Color
  108111. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  108112. // Scale / offset
  108113. currentEffect.setVector2("offset", this.offset);
  108114. currentEffect.setVector2("scale", this.scale);
  108115. // VBOs
  108116. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  108117. // Draw order
  108118. if (!this.alphaTest) {
  108119. engine.setAlphaMode(this.alphaBlendingMode);
  108120. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108121. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108122. }
  108123. else {
  108124. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108125. }
  108126. this.onAfterRenderObservable.notifyObservers(this);
  108127. };
  108128. /**
  108129. * Disposes and releases the associated ressources.
  108130. */
  108131. Layer.prototype.dispose = function () {
  108132. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108133. if (vertexBuffer) {
  108134. vertexBuffer.dispose();
  108135. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  108136. }
  108137. if (this._indexBuffer) {
  108138. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  108139. this._indexBuffer = null;
  108140. }
  108141. if (this.texture) {
  108142. this.texture.dispose();
  108143. this.texture = null;
  108144. }
  108145. // Remove from scene
  108146. var index = this._scene.layers.indexOf(this);
  108147. this._scene.layers.splice(index, 1);
  108148. // Callback
  108149. this.onDisposeObservable.notifyObservers(this);
  108150. this.onDisposeObservable.clear();
  108151. this.onAfterRenderObservable.clear();
  108152. this.onBeforeRenderObservable.clear();
  108153. };
  108154. return Layer;
  108155. }());
  108156. BABYLON.Layer = Layer;
  108157. })(BABYLON || (BABYLON = {}));
  108158. //# sourceMappingURL=babylon.layer.js.map
  108159. var BABYLON;
  108160. (function (BABYLON) {
  108161. var TextureTools = /** @class */ (function () {
  108162. function TextureTools() {
  108163. }
  108164. /**
  108165. * Uses the GPU to create a copy texture rescaled at a given size
  108166. * @param texture Texture to copy from
  108167. * @param width Desired width
  108168. * @param height Desired height
  108169. * @return Generated texture
  108170. */
  108171. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  108172. if (useBilinearMode === void 0) { useBilinearMode = true; }
  108173. var scene = texture.getScene();
  108174. var engine = scene.getEngine();
  108175. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  108176. rtt.wrapU = texture.wrapU;
  108177. rtt.wrapV = texture.wrapV;
  108178. rtt.uOffset = texture.uOffset;
  108179. rtt.vOffset = texture.vOffset;
  108180. rtt.uScale = texture.uScale;
  108181. rtt.vScale = texture.vScale;
  108182. rtt.uAng = texture.uAng;
  108183. rtt.vAng = texture.vAng;
  108184. rtt.wAng = texture.wAng;
  108185. rtt.coordinatesIndex = texture.coordinatesIndex;
  108186. rtt.level = texture.level;
  108187. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  108188. rtt._texture.isReady = false;
  108189. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108190. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108191. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108192. passPostProcess.getEffect().executeWhenCompiled(function () {
  108193. passPostProcess.onApply = function (effect) {
  108194. effect.setTexture("textureSampler", texture);
  108195. };
  108196. var internalTexture = rtt.getInternalTexture();
  108197. if (internalTexture) {
  108198. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  108199. engine.unBindFramebuffer(internalTexture);
  108200. rtt.disposeFramebufferObjects();
  108201. passPostProcess.dispose();
  108202. internalTexture.isReady = true;
  108203. }
  108204. });
  108205. return rtt;
  108206. };
  108207. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  108208. if (!scene._environmentBRDFTexture) {
  108209. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108210. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108211. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108212. scene._environmentBRDFTexture = texture;
  108213. }
  108214. return scene._environmentBRDFTexture;
  108215. };
  108216. 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=";
  108217. return TextureTools;
  108218. }());
  108219. BABYLON.TextureTools = TextureTools;
  108220. })(BABYLON || (BABYLON = {}));
  108221. //# sourceMappingURL=babylon.textureTools.js.map
  108222. var BABYLON;
  108223. (function (BABYLON) {
  108224. /**
  108225. * 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.
  108226. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  108227. */
  108228. var FramingBehavior = /** @class */ (function () {
  108229. function FramingBehavior() {
  108230. this._mode = FramingBehavior.FitFrustumSidesMode;
  108231. this._radiusScale = 1.0;
  108232. this._positionScale = 0.5;
  108233. this._defaultElevation = 0.3;
  108234. this._elevationReturnTime = 1500;
  108235. this._elevationReturnWaitTime = 1000;
  108236. this._zoomStopsAnimation = false;
  108237. this._framingTime = 1500;
  108238. /**
  108239. * Define if the behavior should automatically change the configured
  108240. * camera limits and sensibilities.
  108241. */
  108242. this.autoCorrectCameraLimitsAndSensibility = true;
  108243. this._isPointerDown = false;
  108244. this._lastInteractionTime = -Infinity;
  108245. // Framing control
  108246. this._animatables = new Array();
  108247. this._betaIsAnimating = false;
  108248. }
  108249. Object.defineProperty(FramingBehavior.prototype, "name", {
  108250. /**
  108251. * Gets the name of the behavior.
  108252. */
  108253. get: function () {
  108254. return "Framing";
  108255. },
  108256. enumerable: true,
  108257. configurable: true
  108258. });
  108259. Object.defineProperty(FramingBehavior.prototype, "mode", {
  108260. /**
  108261. * Gets current mode used by the behavior.
  108262. */
  108263. get: function () {
  108264. return this._mode;
  108265. },
  108266. /**
  108267. * Sets the current mode used by the behavior
  108268. */
  108269. set: function (mode) {
  108270. this._mode = mode;
  108271. },
  108272. enumerable: true,
  108273. configurable: true
  108274. });
  108275. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  108276. /**
  108277. * Gets the scale applied to the radius
  108278. */
  108279. get: function () {
  108280. return this._radiusScale;
  108281. },
  108282. /**
  108283. * Sets the scale applied to the radius (1 by default)
  108284. */
  108285. set: function (radius) {
  108286. this._radiusScale = radius;
  108287. },
  108288. enumerable: true,
  108289. configurable: true
  108290. });
  108291. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  108292. /**
  108293. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108294. */
  108295. get: function () {
  108296. return this._positionScale;
  108297. },
  108298. /**
  108299. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108300. */
  108301. set: function (scale) {
  108302. this._positionScale = scale;
  108303. },
  108304. enumerable: true,
  108305. configurable: true
  108306. });
  108307. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  108308. /**
  108309. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108310. * behaviour is triggered, in radians.
  108311. */
  108312. get: function () {
  108313. return this._defaultElevation;
  108314. },
  108315. /**
  108316. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108317. * behaviour is triggered, in radians.
  108318. */
  108319. set: function (elevation) {
  108320. this._defaultElevation = elevation;
  108321. },
  108322. enumerable: true,
  108323. configurable: true
  108324. });
  108325. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  108326. /**
  108327. * Gets the time (in milliseconds) taken to return to the default beta position.
  108328. * Negative value indicates camera should not return to default.
  108329. */
  108330. get: function () {
  108331. return this._elevationReturnTime;
  108332. },
  108333. /**
  108334. * Sets the time (in milliseconds) taken to return to the default beta position.
  108335. * Negative value indicates camera should not return to default.
  108336. */
  108337. set: function (speed) {
  108338. this._elevationReturnTime = speed;
  108339. },
  108340. enumerable: true,
  108341. configurable: true
  108342. });
  108343. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  108344. /**
  108345. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108346. */
  108347. get: function () {
  108348. return this._elevationReturnWaitTime;
  108349. },
  108350. /**
  108351. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108352. */
  108353. set: function (time) {
  108354. this._elevationReturnWaitTime = time;
  108355. },
  108356. enumerable: true,
  108357. configurable: true
  108358. });
  108359. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  108360. /**
  108361. * Gets the flag that indicates if user zooming should stop animation.
  108362. */
  108363. get: function () {
  108364. return this._zoomStopsAnimation;
  108365. },
  108366. /**
  108367. * Sets the flag that indicates if user zooming should stop animation.
  108368. */
  108369. set: function (flag) {
  108370. this._zoomStopsAnimation = flag;
  108371. },
  108372. enumerable: true,
  108373. configurable: true
  108374. });
  108375. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  108376. /**
  108377. * Gets the transition time when framing the mesh, in milliseconds
  108378. */
  108379. get: function () {
  108380. return this._framingTime;
  108381. },
  108382. /**
  108383. * Sets the transition time when framing the mesh, in milliseconds
  108384. */
  108385. set: function (time) {
  108386. this._framingTime = time;
  108387. },
  108388. enumerable: true,
  108389. configurable: true
  108390. });
  108391. /**
  108392. * Initializes the behavior.
  108393. */
  108394. FramingBehavior.prototype.init = function () {
  108395. // Do notihng
  108396. };
  108397. /**
  108398. * Attaches the behavior to its arc rotate camera.
  108399. * @param camera Defines the camera to attach the behavior to
  108400. */
  108401. FramingBehavior.prototype.attach = function (camera) {
  108402. var _this = this;
  108403. this._attachedCamera = camera;
  108404. var scene = this._attachedCamera.getScene();
  108405. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  108406. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  108407. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  108408. _this._isPointerDown = true;
  108409. return;
  108410. }
  108411. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  108412. _this._isPointerDown = false;
  108413. }
  108414. });
  108415. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108416. if (mesh) {
  108417. _this.zoomOnMesh(mesh);
  108418. }
  108419. });
  108420. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108421. // Stop the animation if there is user interaction and the animation should stop for this interaction
  108422. _this._applyUserInteraction();
  108423. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  108424. // back to the default position after a given timeout
  108425. _this._maintainCameraAboveGround();
  108426. });
  108427. };
  108428. /**
  108429. * Detaches the behavior from its current arc rotate camera.
  108430. */
  108431. FramingBehavior.prototype.detach = function () {
  108432. if (!this._attachedCamera) {
  108433. return;
  108434. }
  108435. var scene = this._attachedCamera.getScene();
  108436. if (this._onPrePointerObservableObserver) {
  108437. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  108438. }
  108439. if (this._onAfterCheckInputsObserver) {
  108440. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108441. }
  108442. if (this._onMeshTargetChangedObserver) {
  108443. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108444. }
  108445. this._attachedCamera = null;
  108446. };
  108447. /**
  108448. * Targets the given mesh and updates zoom level accordingly.
  108449. * @param mesh The mesh to target.
  108450. * @param radius Optional. If a cached radius position already exists, overrides default.
  108451. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108452. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108453. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108454. */
  108455. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108456. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108457. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108458. mesh.computeWorldMatrix(true);
  108459. var boundingBox = mesh.getBoundingInfo().boundingBox;
  108460. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  108461. };
  108462. /**
  108463. * Targets the given mesh with its children and updates zoom level accordingly.
  108464. * @param mesh The mesh to target.
  108465. * @param radius Optional. If a cached radius position already exists, overrides default.
  108466. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108467. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108468. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108469. */
  108470. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108471. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108472. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108473. mesh.computeWorldMatrix(true);
  108474. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  108475. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  108476. };
  108477. /**
  108478. * Targets the given meshes with their children and updates zoom level accordingly.
  108479. * @param meshes The mesh to target.
  108480. * @param radius Optional. If a cached radius position already exists, overrides default.
  108481. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108482. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108483. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108484. */
  108485. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  108486. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108487. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108488. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  108489. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  108490. for (var i = 0; i < meshes.length; i++) {
  108491. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  108492. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  108493. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  108494. }
  108495. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  108496. };
  108497. /**
  108498. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  108499. * @param minimumWorld Determines the smaller position of the bounding box extend
  108500. * @param maximumWorld Determines the bigger position of the bounding box extend
  108501. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108502. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108503. */
  108504. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  108505. var _this = this;
  108506. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108507. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108508. var zoomTarget;
  108509. if (!this._attachedCamera) {
  108510. return;
  108511. }
  108512. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  108513. var bottom = minimumWorld.y;
  108514. var top = maximumWorld.y;
  108515. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  108516. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  108517. if (focusOnOriginXZ) {
  108518. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  108519. }
  108520. else {
  108521. var centerWorld = minimumWorld.add(radiusWorld);
  108522. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  108523. }
  108524. if (!this._vectorTransition) {
  108525. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  108526. }
  108527. this._betaIsAnimating = true;
  108528. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  108529. if (animatable) {
  108530. this._animatables.push(animatable);
  108531. }
  108532. // sets the radius and lower radius bounds
  108533. // Small delta ensures camera is not always at lower zoom limit.
  108534. var radius = 0;
  108535. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  108536. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108537. if (this.autoCorrectCameraLimitsAndSensibility) {
  108538. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  108539. }
  108540. radius = position;
  108541. }
  108542. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108543. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108544. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  108545. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  108546. }
  108547. }
  108548. // Set sensibilities
  108549. if (this.autoCorrectCameraLimitsAndSensibility) {
  108550. var extend = maximumWorld.subtract(minimumWorld).length();
  108551. this._attachedCamera.panningSensibility = 5000 / extend;
  108552. this._attachedCamera.wheelPrecision = 100 / radius;
  108553. }
  108554. // transition to new radius
  108555. if (!this._radiusTransition) {
  108556. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108557. }
  108558. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  108559. _this.stopAllAnimations();
  108560. if (onAnimationEnd) {
  108561. onAnimationEnd();
  108562. }
  108563. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  108564. _this._attachedCamera.storeState();
  108565. }
  108566. });
  108567. if (animatable) {
  108568. this._animatables.push(animatable);
  108569. }
  108570. };
  108571. /**
  108572. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  108573. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  108574. * frustum width.
  108575. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  108576. * to fully enclose the mesh in the viewing frustum.
  108577. */
  108578. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  108579. var size = maximumWorld.subtract(minimumWorld);
  108580. var boxVectorGlobalDiagonal = size.length();
  108581. var frustumSlope = this._getFrustumSlope();
  108582. // Formula for setting distance
  108583. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  108584. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  108585. // Horizon distance
  108586. var radius = radiusWithoutFraming * this._radiusScale;
  108587. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  108588. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  108589. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  108590. var camera = this._attachedCamera;
  108591. if (!camera) {
  108592. return 0;
  108593. }
  108594. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108595. // Don't exceed the requested limit
  108596. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  108597. }
  108598. // Don't exceed the upper radius limit
  108599. if (camera.upperRadiusLimit) {
  108600. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  108601. }
  108602. return distance;
  108603. };
  108604. /**
  108605. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  108606. * is automatically returned to its default position (expected to be above ground plane).
  108607. */
  108608. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  108609. var _this = this;
  108610. if (this._elevationReturnTime < 0) {
  108611. return;
  108612. }
  108613. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  108614. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  108615. var limitBeta = Math.PI * 0.5;
  108616. // Bring the camera back up if below the ground plane
  108617. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  108618. this._betaIsAnimating = true;
  108619. //Transition to new position
  108620. this.stopAllAnimations();
  108621. if (!this._betaTransition) {
  108622. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108623. }
  108624. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  108625. _this._clearAnimationLocks();
  108626. _this.stopAllAnimations();
  108627. });
  108628. if (animatabe) {
  108629. this._animatables.push(animatabe);
  108630. }
  108631. }
  108632. };
  108633. /**
  108634. * Returns the frustum slope based on the canvas ratio and camera FOV
  108635. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  108636. */
  108637. FramingBehavior.prototype._getFrustumSlope = function () {
  108638. // Calculate the viewport ratio
  108639. // Aspect Ratio is Height/Width.
  108640. var camera = this._attachedCamera;
  108641. if (!camera) {
  108642. return BABYLON.Vector2.Zero();
  108643. }
  108644. var engine = camera.getScene().getEngine();
  108645. var aspectRatio = engine.getAspectRatio(camera);
  108646. // Camera FOV is the vertical field of view (top-bottom) in radians.
  108647. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  108648. var frustumSlopeY = Math.tan(camera.fov / 2);
  108649. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  108650. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  108651. // along the forward vector.
  108652. var frustumSlopeX = frustumSlopeY * aspectRatio;
  108653. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  108654. };
  108655. /**
  108656. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  108657. */
  108658. FramingBehavior.prototype._clearAnimationLocks = function () {
  108659. this._betaIsAnimating = false;
  108660. };
  108661. /**
  108662. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  108663. */
  108664. FramingBehavior.prototype._applyUserInteraction = function () {
  108665. if (this.isUserIsMoving) {
  108666. this._lastInteractionTime = BABYLON.Tools.Now;
  108667. this.stopAllAnimations();
  108668. this._clearAnimationLocks();
  108669. }
  108670. };
  108671. /**
  108672. * Stops and removes all animations that have been applied to the camera
  108673. */
  108674. FramingBehavior.prototype.stopAllAnimations = function () {
  108675. if (this._attachedCamera) {
  108676. this._attachedCamera.animations = [];
  108677. }
  108678. while (this._animatables.length) {
  108679. if (this._animatables[0]) {
  108680. this._animatables[0].onAnimationEnd = null;
  108681. this._animatables[0].stop();
  108682. }
  108683. this._animatables.shift();
  108684. }
  108685. };
  108686. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  108687. /**
  108688. * Gets a value indicating if the user is moving the camera
  108689. */
  108690. get: function () {
  108691. if (!this._attachedCamera) {
  108692. return false;
  108693. }
  108694. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108695. this._attachedCamera.inertialBetaOffset !== 0 ||
  108696. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108697. this._attachedCamera.inertialPanningX !== 0 ||
  108698. this._attachedCamera.inertialPanningY !== 0 ||
  108699. this._isPointerDown;
  108700. },
  108701. enumerable: true,
  108702. configurable: true
  108703. });
  108704. /**
  108705. * The easing function used by animations
  108706. */
  108707. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  108708. /**
  108709. * The easing mode used by animations
  108710. */
  108711. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  108712. // Statics
  108713. /**
  108714. * The camera can move all the way towards the mesh.
  108715. */
  108716. FramingBehavior.IgnoreBoundsSizeMode = 0;
  108717. /**
  108718. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  108719. */
  108720. FramingBehavior.FitFrustumSidesMode = 1;
  108721. return FramingBehavior;
  108722. }());
  108723. BABYLON.FramingBehavior = FramingBehavior;
  108724. })(BABYLON || (BABYLON = {}));
  108725. //# sourceMappingURL=babylon.framingBehavior.js.map
  108726. var BABYLON;
  108727. (function (BABYLON) {
  108728. /**
  108729. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  108730. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  108731. */
  108732. var BouncingBehavior = /** @class */ (function () {
  108733. function BouncingBehavior() {
  108734. /**
  108735. * The duration of the animation, in milliseconds
  108736. */
  108737. this.transitionDuration = 450;
  108738. /**
  108739. * Length of the distance animated by the transition when lower radius is reached
  108740. */
  108741. this.lowerRadiusTransitionRange = 2;
  108742. /**
  108743. * Length of the distance animated by the transition when upper radius is reached
  108744. */
  108745. this.upperRadiusTransitionRange = -2;
  108746. this._autoTransitionRange = false;
  108747. // Animations
  108748. this._radiusIsAnimating = false;
  108749. this._radiusBounceTransition = null;
  108750. this._animatables = new Array();
  108751. }
  108752. Object.defineProperty(BouncingBehavior.prototype, "name", {
  108753. /**
  108754. * Gets the name of the behavior.
  108755. */
  108756. get: function () {
  108757. return "Bouncing";
  108758. },
  108759. enumerable: true,
  108760. configurable: true
  108761. });
  108762. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  108763. /**
  108764. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108765. */
  108766. get: function () {
  108767. return this._autoTransitionRange;
  108768. },
  108769. /**
  108770. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108771. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  108772. */
  108773. set: function (value) {
  108774. var _this = this;
  108775. if (this._autoTransitionRange === value) {
  108776. return;
  108777. }
  108778. this._autoTransitionRange = value;
  108779. var camera = this._attachedCamera;
  108780. if (!camera) {
  108781. return;
  108782. }
  108783. if (value) {
  108784. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108785. if (!mesh) {
  108786. return;
  108787. }
  108788. mesh.computeWorldMatrix(true);
  108789. var diagonal = mesh.getBoundingInfo().diagonalLength;
  108790. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  108791. _this.upperRadiusTransitionRange = diagonal * 0.05;
  108792. });
  108793. }
  108794. else if (this._onMeshTargetChangedObserver) {
  108795. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108796. }
  108797. },
  108798. enumerable: true,
  108799. configurable: true
  108800. });
  108801. /**
  108802. * Initializes the behavior.
  108803. */
  108804. BouncingBehavior.prototype.init = function () {
  108805. // Do notihng
  108806. };
  108807. /**
  108808. * Attaches the behavior to its arc rotate camera.
  108809. * @param camera Defines the camera to attach the behavior to
  108810. */
  108811. BouncingBehavior.prototype.attach = function (camera) {
  108812. var _this = this;
  108813. this._attachedCamera = camera;
  108814. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108815. if (!_this._attachedCamera) {
  108816. return;
  108817. }
  108818. // Add the bounce animation to the lower radius limit
  108819. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  108820. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  108821. }
  108822. // Add the bounce animation to the upper radius limit
  108823. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  108824. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  108825. }
  108826. });
  108827. };
  108828. /**
  108829. * Detaches the behavior from its current arc rotate camera.
  108830. */
  108831. BouncingBehavior.prototype.detach = function () {
  108832. if (!this._attachedCamera) {
  108833. return;
  108834. }
  108835. if (this._onAfterCheckInputsObserver) {
  108836. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108837. }
  108838. if (this._onMeshTargetChangedObserver) {
  108839. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108840. }
  108841. this._attachedCamera = null;
  108842. };
  108843. /**
  108844. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  108845. * @param radiusLimit The limit to check against.
  108846. * @return Bool to indicate if at limit.
  108847. */
  108848. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  108849. if (!this._attachedCamera) {
  108850. return false;
  108851. }
  108852. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  108853. return true;
  108854. }
  108855. return false;
  108856. };
  108857. /**
  108858. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  108859. * @param radiusDelta The delta by which to animate to. Can be negative.
  108860. */
  108861. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  108862. var _this = this;
  108863. if (!this._attachedCamera) {
  108864. return;
  108865. }
  108866. if (!this._radiusBounceTransition) {
  108867. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  108868. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  108869. }
  108870. // Prevent zoom until bounce has completed
  108871. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  108872. this._attachedCamera.wheelPrecision = Infinity;
  108873. this._attachedCamera.inertialRadiusOffset = 0;
  108874. // Animate to the radius limit
  108875. this.stopAllAnimations();
  108876. this._radiusIsAnimating = true;
  108877. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  108878. if (animatable) {
  108879. this._animatables.push(animatable);
  108880. }
  108881. };
  108882. /**
  108883. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  108884. */
  108885. BouncingBehavior.prototype._clearAnimationLocks = function () {
  108886. this._radiusIsAnimating = false;
  108887. if (this._attachedCamera) {
  108888. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  108889. }
  108890. };
  108891. /**
  108892. * Stops and removes all animations that have been applied to the camera
  108893. */
  108894. BouncingBehavior.prototype.stopAllAnimations = function () {
  108895. if (this._attachedCamera) {
  108896. this._attachedCamera.animations = [];
  108897. }
  108898. while (this._animatables.length) {
  108899. this._animatables[0].onAnimationEnd = null;
  108900. this._animatables[0].stop();
  108901. this._animatables.shift();
  108902. }
  108903. };
  108904. /**
  108905. * The easing function used by animations
  108906. */
  108907. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  108908. /**
  108909. * The easing mode used by animations
  108910. */
  108911. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  108912. return BouncingBehavior;
  108913. }());
  108914. BABYLON.BouncingBehavior = BouncingBehavior;
  108915. })(BABYLON || (BABYLON = {}));
  108916. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  108917. var BABYLON;
  108918. (function (BABYLON) {
  108919. /**
  108920. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  108921. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  108922. */
  108923. var AutoRotationBehavior = /** @class */ (function () {
  108924. function AutoRotationBehavior() {
  108925. this._zoomStopsAnimation = false;
  108926. this._idleRotationSpeed = 0.05;
  108927. this._idleRotationWaitTime = 2000;
  108928. this._idleRotationSpinupTime = 2000;
  108929. this._isPointerDown = false;
  108930. this._lastFrameTime = null;
  108931. this._lastInteractionTime = -Infinity;
  108932. this._cameraRotationSpeed = 0;
  108933. this._lastFrameRadius = 0;
  108934. }
  108935. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  108936. /**
  108937. * Gets the name of the behavior.
  108938. */
  108939. get: function () {
  108940. return "AutoRotation";
  108941. },
  108942. enumerable: true,
  108943. configurable: true
  108944. });
  108945. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  108946. /**
  108947. * Gets the flag that indicates if user zooming should stop animation.
  108948. */
  108949. get: function () {
  108950. return this._zoomStopsAnimation;
  108951. },
  108952. /**
  108953. * Sets the flag that indicates if user zooming should stop animation.
  108954. */
  108955. set: function (flag) {
  108956. this._zoomStopsAnimation = flag;
  108957. },
  108958. enumerable: true,
  108959. configurable: true
  108960. });
  108961. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  108962. /**
  108963. * Gets the default speed at which the camera rotates around the model.
  108964. */
  108965. get: function () {
  108966. return this._idleRotationSpeed;
  108967. },
  108968. /**
  108969. * Sets the default speed at which the camera rotates around the model.
  108970. */
  108971. set: function (speed) {
  108972. this._idleRotationSpeed = speed;
  108973. },
  108974. enumerable: true,
  108975. configurable: true
  108976. });
  108977. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  108978. /**
  108979. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  108980. */
  108981. get: function () {
  108982. return this._idleRotationWaitTime;
  108983. },
  108984. /**
  108985. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  108986. */
  108987. set: function (time) {
  108988. this._idleRotationWaitTime = time;
  108989. },
  108990. enumerable: true,
  108991. configurable: true
  108992. });
  108993. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  108994. /**
  108995. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  108996. */
  108997. get: function () {
  108998. return this._idleRotationSpinupTime;
  108999. },
  109000. /**
  109001. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109002. */
  109003. set: function (time) {
  109004. this._idleRotationSpinupTime = time;
  109005. },
  109006. enumerable: true,
  109007. configurable: true
  109008. });
  109009. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  109010. /**
  109011. * Gets a value indicating if the camera is currently rotating because of this behavior
  109012. */
  109013. get: function () {
  109014. return Math.abs(this._cameraRotationSpeed) > 0;
  109015. },
  109016. enumerable: true,
  109017. configurable: true
  109018. });
  109019. /**
  109020. * Initializes the behavior.
  109021. */
  109022. AutoRotationBehavior.prototype.init = function () {
  109023. // Do notihng
  109024. };
  109025. /**
  109026. * Attaches the behavior to its arc rotate camera.
  109027. * @param camera Defines the camera to attach the behavior to
  109028. */
  109029. AutoRotationBehavior.prototype.attach = function (camera) {
  109030. var _this = this;
  109031. this._attachedCamera = camera;
  109032. var scene = this._attachedCamera.getScene();
  109033. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109034. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109035. _this._isPointerDown = true;
  109036. return;
  109037. }
  109038. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109039. _this._isPointerDown = false;
  109040. }
  109041. });
  109042. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109043. var now = BABYLON.Tools.Now;
  109044. var dt = 0;
  109045. if (_this._lastFrameTime != null) {
  109046. dt = now - _this._lastFrameTime;
  109047. }
  109048. _this._lastFrameTime = now;
  109049. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109050. _this._applyUserInteraction();
  109051. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  109052. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  109053. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  109054. // Step camera rotation by rotation speed
  109055. if (_this._attachedCamera) {
  109056. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  109057. }
  109058. });
  109059. };
  109060. /**
  109061. * Detaches the behavior from its current arc rotate camera.
  109062. */
  109063. AutoRotationBehavior.prototype.detach = function () {
  109064. if (!this._attachedCamera) {
  109065. return;
  109066. }
  109067. var scene = this._attachedCamera.getScene();
  109068. if (this._onPrePointerObservableObserver) {
  109069. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109070. }
  109071. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109072. this._attachedCamera = null;
  109073. };
  109074. /**
  109075. * Returns true if user is scrolling.
  109076. * @return true if user is scrolling.
  109077. */
  109078. AutoRotationBehavior.prototype._userIsZooming = function () {
  109079. if (!this._attachedCamera) {
  109080. return false;
  109081. }
  109082. return this._attachedCamera.inertialRadiusOffset !== 0;
  109083. };
  109084. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  109085. if (!this._attachedCamera) {
  109086. return false;
  109087. }
  109088. var zoomHasHitLimit = false;
  109089. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  109090. zoomHasHitLimit = true;
  109091. }
  109092. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  109093. this._lastFrameRadius = this._attachedCamera.radius;
  109094. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  109095. };
  109096. /**
  109097. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109098. */
  109099. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  109100. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  109101. this._lastInteractionTime = BABYLON.Tools.Now;
  109102. }
  109103. };
  109104. // Tools
  109105. AutoRotationBehavior.prototype._userIsMoving = function () {
  109106. if (!this._attachedCamera) {
  109107. return false;
  109108. }
  109109. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109110. this._attachedCamera.inertialBetaOffset !== 0 ||
  109111. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109112. this._attachedCamera.inertialPanningX !== 0 ||
  109113. this._attachedCamera.inertialPanningY !== 0 ||
  109114. this._isPointerDown;
  109115. };
  109116. return AutoRotationBehavior;
  109117. }());
  109118. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  109119. })(BABYLON || (BABYLON = {}));
  109120. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  109121. var BABYLON;
  109122. (function (BABYLON) {
  109123. var NullEngineOptions = /** @class */ (function () {
  109124. function NullEngineOptions() {
  109125. this.renderWidth = 512;
  109126. this.renderHeight = 256;
  109127. this.textureSize = 512;
  109128. this.deterministicLockstep = false;
  109129. this.lockstepMaxSteps = 4;
  109130. }
  109131. return NullEngineOptions;
  109132. }());
  109133. BABYLON.NullEngineOptions = NullEngineOptions;
  109134. /**
  109135. * The null engine class provides support for headless version of babylon.js.
  109136. * This can be used in server side scenario or for testing purposes
  109137. */
  109138. var NullEngine = /** @class */ (function (_super) {
  109139. __extends(NullEngine, _super);
  109140. function NullEngine(options) {
  109141. if (options === void 0) { options = new NullEngineOptions(); }
  109142. var _this = _super.call(this, null) || this;
  109143. if (options.deterministicLockstep === undefined) {
  109144. options.deterministicLockstep = false;
  109145. }
  109146. if (options.lockstepMaxSteps === undefined) {
  109147. options.lockstepMaxSteps = 4;
  109148. }
  109149. _this._options = options;
  109150. // Init caps
  109151. // We consider we are on a webgl1 capable device
  109152. _this._caps = new BABYLON.EngineCapabilities();
  109153. _this._caps.maxTexturesImageUnits = 16;
  109154. _this._caps.maxVertexTextureImageUnits = 16;
  109155. _this._caps.maxTextureSize = 512;
  109156. _this._caps.maxCubemapTextureSize = 512;
  109157. _this._caps.maxRenderTextureSize = 512;
  109158. _this._caps.maxVertexAttribs = 16;
  109159. _this._caps.maxVaryingVectors = 16;
  109160. _this._caps.maxFragmentUniformVectors = 16;
  109161. _this._caps.maxVertexUniformVectors = 16;
  109162. // Extensions
  109163. _this._caps.standardDerivatives = false;
  109164. _this._caps.astc = null;
  109165. _this._caps.s3tc = null;
  109166. _this._caps.pvrtc = null;
  109167. _this._caps.etc1 = null;
  109168. _this._caps.etc2 = null;
  109169. _this._caps.textureAnisotropicFilterExtension = null;
  109170. _this._caps.maxAnisotropy = 0;
  109171. _this._caps.uintIndices = false;
  109172. _this._caps.fragmentDepthSupported = false;
  109173. _this._caps.highPrecisionShaderSupported = true;
  109174. _this._caps.colorBufferFloat = false;
  109175. _this._caps.textureFloat = false;
  109176. _this._caps.textureFloatLinearFiltering = false;
  109177. _this._caps.textureFloatRender = false;
  109178. _this._caps.textureHalfFloat = false;
  109179. _this._caps.textureHalfFloatLinearFiltering = false;
  109180. _this._caps.textureHalfFloatRender = false;
  109181. _this._caps.textureLOD = false;
  109182. _this._caps.drawBuffersExtension = false;
  109183. _this._caps.depthTextureExtension = false;
  109184. _this._caps.vertexArrayObject = false;
  109185. _this._caps.instancedArrays = false;
  109186. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  109187. // Wrappers
  109188. if (typeof URL === "undefined") {
  109189. URL = {
  109190. createObjectURL: function () { },
  109191. revokeObjectURL: function () { }
  109192. };
  109193. }
  109194. if (typeof Blob === "undefined") {
  109195. Blob = function () { };
  109196. }
  109197. return _this;
  109198. }
  109199. NullEngine.prototype.isDeterministicLockStep = function () {
  109200. return this._options.deterministicLockstep;
  109201. };
  109202. NullEngine.prototype.getLockstepMaxSteps = function () {
  109203. return this._options.lockstepMaxSteps;
  109204. };
  109205. NullEngine.prototype.getHardwareScalingLevel = function () {
  109206. return 1.0;
  109207. };
  109208. NullEngine.prototype.createVertexBuffer = function (vertices) {
  109209. return {
  109210. capacity: 0,
  109211. references: 1,
  109212. is32Bits: false
  109213. };
  109214. };
  109215. NullEngine.prototype.createIndexBuffer = function (indices) {
  109216. return {
  109217. capacity: 0,
  109218. references: 1,
  109219. is32Bits: false
  109220. };
  109221. };
  109222. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  109223. if (stencil === void 0) { stencil = false; }
  109224. };
  109225. NullEngine.prototype.getRenderWidth = function (useScreen) {
  109226. if (useScreen === void 0) { useScreen = false; }
  109227. if (!useScreen && this._currentRenderTarget) {
  109228. return this._currentRenderTarget.width;
  109229. }
  109230. return this._options.renderWidth;
  109231. };
  109232. NullEngine.prototype.getRenderHeight = function (useScreen) {
  109233. if (useScreen === void 0) { useScreen = false; }
  109234. if (!useScreen && this._currentRenderTarget) {
  109235. return this._currentRenderTarget.height;
  109236. }
  109237. return this._options.renderHeight;
  109238. };
  109239. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  109240. this._cachedViewport = viewport;
  109241. };
  109242. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  109243. return {
  109244. transformFeedback: null,
  109245. __SPECTOR_rebuildProgram: null
  109246. };
  109247. };
  109248. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  109249. return [];
  109250. };
  109251. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  109252. return [];
  109253. };
  109254. NullEngine.prototype.bindSamplers = function (effect) {
  109255. this._currentEffect = null;
  109256. };
  109257. NullEngine.prototype.enableEffect = function (effect) {
  109258. this._currentEffect = effect;
  109259. if (effect.onBind) {
  109260. effect.onBind(effect);
  109261. }
  109262. if (effect._onBindObservable) {
  109263. effect._onBindObservable.notifyObservers(effect);
  109264. }
  109265. };
  109266. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  109267. if (zOffset === void 0) { zOffset = 0; }
  109268. if (reverseSide === void 0) { reverseSide = false; }
  109269. };
  109270. NullEngine.prototype.setIntArray = function (uniform, array) {
  109271. };
  109272. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  109273. };
  109274. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  109275. };
  109276. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  109277. };
  109278. NullEngine.prototype.setFloatArray = function (uniform, array) {
  109279. };
  109280. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  109281. };
  109282. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  109283. };
  109284. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  109285. };
  109286. NullEngine.prototype.setArray = function (uniform, array) {
  109287. };
  109288. NullEngine.prototype.setArray2 = function (uniform, array) {
  109289. };
  109290. NullEngine.prototype.setArray3 = function (uniform, array) {
  109291. };
  109292. NullEngine.prototype.setArray4 = function (uniform, array) {
  109293. };
  109294. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  109295. };
  109296. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  109297. };
  109298. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  109299. };
  109300. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  109301. };
  109302. NullEngine.prototype.setFloat = function (uniform, value) {
  109303. };
  109304. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  109305. };
  109306. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  109307. };
  109308. NullEngine.prototype.setBool = function (uniform, bool) {
  109309. };
  109310. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  109311. };
  109312. NullEngine.prototype.setColor3 = function (uniform, color3) {
  109313. };
  109314. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  109315. };
  109316. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  109317. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  109318. if (this._alphaMode === mode) {
  109319. return;
  109320. }
  109321. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  109322. if (!noDepthWriteChange) {
  109323. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  109324. }
  109325. this._alphaMode = mode;
  109326. };
  109327. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  109328. };
  109329. NullEngine.prototype.wipeCaches = function (bruteForce) {
  109330. if (this.preventCacheWipeBetweenFrames) {
  109331. return;
  109332. }
  109333. this.resetTextureCache();
  109334. this._currentEffect = null;
  109335. if (bruteForce) {
  109336. this._currentProgram = null;
  109337. this._stencilState.reset();
  109338. this._depthCullingState.reset();
  109339. this._alphaState.reset();
  109340. }
  109341. this._cachedVertexBuffers = null;
  109342. this._cachedIndexBuffer = null;
  109343. this._cachedEffectForVertexBuffers = null;
  109344. };
  109345. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  109346. };
  109347. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  109348. };
  109349. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  109350. };
  109351. /** @hidden */
  109352. NullEngine.prototype._createTexture = function () {
  109353. return {};
  109354. };
  109355. /** @hidden */
  109356. NullEngine.prototype._releaseTexture = function (texture) {
  109357. };
  109358. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  109359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109360. if (onLoad === void 0) { onLoad = null; }
  109361. if (onError === void 0) { onError = null; }
  109362. if (buffer === void 0) { buffer = null; }
  109363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  109364. var url = String(urlArg);
  109365. texture.url = url;
  109366. texture.generateMipMaps = !noMipmap;
  109367. texture.samplingMode = samplingMode;
  109368. texture.invertY = invertY;
  109369. texture.baseWidth = this._options.textureSize;
  109370. texture.baseHeight = this._options.textureSize;
  109371. texture.width = this._options.textureSize;
  109372. texture.height = this._options.textureSize;
  109373. if (format) {
  109374. texture.format = format;
  109375. }
  109376. texture.isReady = true;
  109377. if (onLoad) {
  109378. onLoad();
  109379. }
  109380. this._internalTexturesCache.push(texture);
  109381. return texture;
  109382. };
  109383. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  109384. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  109385. if (options !== undefined && typeof options === "object") {
  109386. fullOptions.generateMipMaps = options.generateMipMaps;
  109387. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  109388. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  109389. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  109390. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  109391. }
  109392. else {
  109393. fullOptions.generateMipMaps = options;
  109394. fullOptions.generateDepthBuffer = true;
  109395. fullOptions.generateStencilBuffer = false;
  109396. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109397. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  109398. }
  109399. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  109400. var width = size.width || size;
  109401. var height = size.height || size;
  109402. texture._depthStencilBuffer = {};
  109403. texture._framebuffer = {};
  109404. texture.baseWidth = width;
  109405. texture.baseHeight = height;
  109406. texture.width = width;
  109407. texture.height = height;
  109408. texture.isReady = true;
  109409. texture.samples = 1;
  109410. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  109411. texture.samplingMode = fullOptions.samplingMode;
  109412. texture.type = fullOptions.type;
  109413. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  109414. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  109415. this._internalTexturesCache.push(texture);
  109416. return texture;
  109417. };
  109418. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  109419. texture.samplingMode = samplingMode;
  109420. };
  109421. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  109422. if (this._currentRenderTarget) {
  109423. this.unBindFramebuffer(this._currentRenderTarget);
  109424. }
  109425. this._currentRenderTarget = texture;
  109426. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  109427. if (this._cachedViewport && !forceFullscreenViewport) {
  109428. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  109429. }
  109430. };
  109431. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  109432. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  109433. this._currentRenderTarget = null;
  109434. if (onBeforeUnbind) {
  109435. if (texture._MSAAFramebuffer) {
  109436. this._currentFramebuffer = texture._framebuffer;
  109437. }
  109438. onBeforeUnbind();
  109439. }
  109440. this._currentFramebuffer = null;
  109441. };
  109442. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  109443. var vbo = {
  109444. capacity: 1,
  109445. references: 1,
  109446. is32Bits: false
  109447. };
  109448. return vbo;
  109449. };
  109450. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  109451. if (premulAlpha === void 0) { premulAlpha = false; }
  109452. };
  109453. /**
  109454. * @hidden
  109455. * Get the current error code of the webGL context
  109456. * @returns the error code
  109457. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  109458. */
  109459. NullEngine.prototype.getError = function () {
  109460. return 0;
  109461. };
  109462. /** @hidden */
  109463. NullEngine.prototype._getUnpackAlignement = function () {
  109464. return 1;
  109465. };
  109466. /** @hidden */
  109467. NullEngine.prototype._unpackFlipY = function (value) {
  109468. };
  109469. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  109470. if (offset === void 0) { offset = 0; }
  109471. };
  109472. /**
  109473. * Updates a dynamic vertex buffer.
  109474. * @param vertexBuffer the vertex buffer to update
  109475. * @param data the data used to update the vertex buffer
  109476. * @param byteOffset the byte offset of the data (optional)
  109477. * @param byteLength the byte length of the data (optional)
  109478. */
  109479. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  109480. };
  109481. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  109482. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  109483. this._boundTexturesCache[this._activeChannel] = texture;
  109484. return true;
  109485. }
  109486. return false;
  109487. };
  109488. /** @hidden */
  109489. NullEngine.prototype._bindTexture = function (channel, texture) {
  109490. if (channel < 0) {
  109491. return;
  109492. }
  109493. this._bindTextureDirectly(0, texture);
  109494. };
  109495. /** @hidden */
  109496. NullEngine.prototype._releaseBuffer = function (buffer) {
  109497. buffer.references--;
  109498. if (buffer.references === 0) {
  109499. return true;
  109500. }
  109501. return false;
  109502. };
  109503. NullEngine.prototype.releaseEffects = function () {
  109504. };
  109505. NullEngine.prototype.displayLoadingUI = function () {
  109506. };
  109507. NullEngine.prototype.hideLoadingUI = function () {
  109508. };
  109509. /** @hidden */
  109510. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  109511. if (faceIndex === void 0) { faceIndex = 0; }
  109512. if (lod === void 0) { lod = 0; }
  109513. };
  109514. /** @hidden */
  109515. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  109516. if (faceIndex === void 0) { faceIndex = 0; }
  109517. if (lod === void 0) { lod = 0; }
  109518. };
  109519. /** @hidden */
  109520. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  109521. if (faceIndex === void 0) { faceIndex = 0; }
  109522. if (lod === void 0) { lod = 0; }
  109523. };
  109524. /** @hidden */
  109525. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  109526. if (faceIndex === void 0) { faceIndex = 0; }
  109527. if (lod === void 0) { lod = 0; }
  109528. };
  109529. return NullEngine;
  109530. }(BABYLON.Engine));
  109531. BABYLON.NullEngine = NullEngine;
  109532. })(BABYLON || (BABYLON = {}));
  109533. //# sourceMappingURL=babylon.nullEngine.js.map
  109534. var BABYLON;
  109535. (function (BABYLON) {
  109536. /**
  109537. * This class can be used to get instrumentation data from a Babylon engine
  109538. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109539. */
  109540. var EngineInstrumentation = /** @class */ (function () {
  109541. /**
  109542. * Instantiates a new engine instrumentation.
  109543. * This class can be used to get instrumentation data from a Babylon engine
  109544. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109545. * @param engine Defines the engine to instrument
  109546. */
  109547. function EngineInstrumentation(
  109548. /**
  109549. * Define the instrumented engine.
  109550. */
  109551. engine) {
  109552. this.engine = engine;
  109553. this._captureGPUFrameTime = false;
  109554. this._gpuFrameTime = new BABYLON.PerfCounter();
  109555. this._captureShaderCompilationTime = false;
  109556. this._shaderCompilationTime = new BABYLON.PerfCounter();
  109557. // Observers
  109558. this._onBeginFrameObserver = null;
  109559. this._onEndFrameObserver = null;
  109560. this._onBeforeShaderCompilationObserver = null;
  109561. this._onAfterShaderCompilationObserver = null;
  109562. }
  109563. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  109564. // Properties
  109565. /**
  109566. * Gets the perf counter used for GPU frame time
  109567. */
  109568. get: function () {
  109569. return this._gpuFrameTime;
  109570. },
  109571. enumerable: true,
  109572. configurable: true
  109573. });
  109574. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  109575. /**
  109576. * Gets the GPU frame time capture status
  109577. */
  109578. get: function () {
  109579. return this._captureGPUFrameTime;
  109580. },
  109581. /**
  109582. * Enable or disable the GPU frame time capture
  109583. */
  109584. set: function (value) {
  109585. var _this = this;
  109586. if (value === this._captureGPUFrameTime) {
  109587. return;
  109588. }
  109589. this._captureGPUFrameTime = value;
  109590. if (value) {
  109591. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  109592. if (!_this._gpuFrameTimeToken) {
  109593. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  109594. }
  109595. });
  109596. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  109597. if (!_this._gpuFrameTimeToken) {
  109598. return;
  109599. }
  109600. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  109601. if (time > -1) {
  109602. _this._gpuFrameTimeToken = null;
  109603. _this._gpuFrameTime.fetchNewFrame();
  109604. _this._gpuFrameTime.addCount(time, true);
  109605. }
  109606. });
  109607. }
  109608. else {
  109609. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109610. this._onBeginFrameObserver = null;
  109611. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109612. this._onEndFrameObserver = null;
  109613. }
  109614. },
  109615. enumerable: true,
  109616. configurable: true
  109617. });
  109618. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  109619. /**
  109620. * Gets the perf counter used for shader compilation time
  109621. */
  109622. get: function () {
  109623. return this._shaderCompilationTime;
  109624. },
  109625. enumerable: true,
  109626. configurable: true
  109627. });
  109628. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  109629. /**
  109630. * Gets the shader compilation time capture status
  109631. */
  109632. get: function () {
  109633. return this._captureShaderCompilationTime;
  109634. },
  109635. /**
  109636. * Enable or disable the shader compilation time capture
  109637. */
  109638. set: function (value) {
  109639. var _this = this;
  109640. if (value === this._captureShaderCompilationTime) {
  109641. return;
  109642. }
  109643. this._captureShaderCompilationTime = value;
  109644. if (value) {
  109645. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  109646. _this._shaderCompilationTime.fetchNewFrame();
  109647. _this._shaderCompilationTime.beginMonitoring();
  109648. });
  109649. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  109650. _this._shaderCompilationTime.endMonitoring();
  109651. });
  109652. }
  109653. else {
  109654. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109655. this._onBeforeShaderCompilationObserver = null;
  109656. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109657. this._onAfterShaderCompilationObserver = null;
  109658. }
  109659. },
  109660. enumerable: true,
  109661. configurable: true
  109662. });
  109663. /**
  109664. * Dispose and release associated resources.
  109665. */
  109666. EngineInstrumentation.prototype.dispose = function () {
  109667. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109668. this._onBeginFrameObserver = null;
  109669. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109670. this._onEndFrameObserver = null;
  109671. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109672. this._onBeforeShaderCompilationObserver = null;
  109673. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109674. this._onAfterShaderCompilationObserver = null;
  109675. this.engine = null;
  109676. };
  109677. return EngineInstrumentation;
  109678. }());
  109679. BABYLON.EngineInstrumentation = EngineInstrumentation;
  109680. })(BABYLON || (BABYLON = {}));
  109681. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  109682. var BABYLON;
  109683. (function (BABYLON) {
  109684. /**
  109685. * This class can be used to get instrumentation data from a Babylon engine
  109686. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109687. */
  109688. var SceneInstrumentation = /** @class */ (function () {
  109689. /**
  109690. * Instantiates a new scene instrumentation.
  109691. * This class can be used to get instrumentation data from a Babylon engine
  109692. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109693. * @param scene Defines the scene to instrument
  109694. */
  109695. function SceneInstrumentation(
  109696. /**
  109697. * Defines the scene to instrument
  109698. */
  109699. scene) {
  109700. var _this = this;
  109701. this.scene = scene;
  109702. this._captureActiveMeshesEvaluationTime = false;
  109703. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  109704. this._captureRenderTargetsRenderTime = false;
  109705. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  109706. this._captureFrameTime = false;
  109707. this._frameTime = new BABYLON.PerfCounter();
  109708. this._captureRenderTime = false;
  109709. this._renderTime = new BABYLON.PerfCounter();
  109710. this._captureInterFrameTime = false;
  109711. this._interFrameTime = new BABYLON.PerfCounter();
  109712. this._captureParticlesRenderTime = false;
  109713. this._particlesRenderTime = new BABYLON.PerfCounter();
  109714. this._captureSpritesRenderTime = false;
  109715. this._spritesRenderTime = new BABYLON.PerfCounter();
  109716. this._capturePhysicsTime = false;
  109717. this._physicsTime = new BABYLON.PerfCounter();
  109718. this._captureAnimationsTime = false;
  109719. this._animationsTime = new BABYLON.PerfCounter();
  109720. this._captureCameraRenderTime = false;
  109721. this._cameraRenderTime = new BABYLON.PerfCounter();
  109722. // Observers
  109723. this._onBeforeActiveMeshesEvaluationObserver = null;
  109724. this._onAfterActiveMeshesEvaluationObserver = null;
  109725. this._onBeforeRenderTargetsRenderObserver = null;
  109726. this._onAfterRenderTargetsRenderObserver = null;
  109727. this._onAfterRenderObserver = null;
  109728. this._onBeforeDrawPhaseObserver = null;
  109729. this._onAfterDrawPhaseObserver = null;
  109730. this._onBeforeAnimationsObserver = null;
  109731. this._onBeforeParticlesRenderingObserver = null;
  109732. this._onAfterParticlesRenderingObserver = null;
  109733. this._onBeforeSpritesRenderingObserver = null;
  109734. this._onAfterSpritesRenderingObserver = null;
  109735. this._onBeforePhysicsObserver = null;
  109736. this._onAfterPhysicsObserver = null;
  109737. this._onAfterAnimationsObserver = null;
  109738. this._onBeforeCameraRenderObserver = null;
  109739. this._onAfterCameraRenderObserver = null;
  109740. // Before render
  109741. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  109742. if (_this._captureActiveMeshesEvaluationTime) {
  109743. _this._activeMeshesEvaluationTime.fetchNewFrame();
  109744. }
  109745. if (_this._captureRenderTargetsRenderTime) {
  109746. _this._renderTargetsRenderTime.fetchNewFrame();
  109747. }
  109748. if (_this._captureFrameTime) {
  109749. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  109750. _this._frameTime.beginMonitoring();
  109751. }
  109752. if (_this._captureInterFrameTime) {
  109753. _this._interFrameTime.endMonitoring();
  109754. }
  109755. if (_this._captureParticlesRenderTime) {
  109756. _this._particlesRenderTime.fetchNewFrame();
  109757. }
  109758. if (_this._captureSpritesRenderTime) {
  109759. _this._spritesRenderTime.fetchNewFrame();
  109760. }
  109761. if (_this._captureAnimationsTime) {
  109762. _this._animationsTime.beginMonitoring();
  109763. }
  109764. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  109765. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  109766. });
  109767. // After render
  109768. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  109769. if (_this._captureFrameTime) {
  109770. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  109771. _this._frameTime.endMonitoring();
  109772. }
  109773. if (_this._captureRenderTime) {
  109774. _this._renderTime.endMonitoring(false);
  109775. }
  109776. if (_this._captureInterFrameTime) {
  109777. _this._interFrameTime.beginMonitoring();
  109778. }
  109779. });
  109780. }
  109781. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  109782. // Properties
  109783. /**
  109784. * Gets the perf counter used for active meshes evaluation time
  109785. */
  109786. get: function () {
  109787. return this._activeMeshesEvaluationTime;
  109788. },
  109789. enumerable: true,
  109790. configurable: true
  109791. });
  109792. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  109793. /**
  109794. * Gets the active meshes evaluation time capture status
  109795. */
  109796. get: function () {
  109797. return this._captureActiveMeshesEvaluationTime;
  109798. },
  109799. /**
  109800. * Enable or disable the active meshes evaluation time capture
  109801. */
  109802. set: function (value) {
  109803. var _this = this;
  109804. if (value === this._captureActiveMeshesEvaluationTime) {
  109805. return;
  109806. }
  109807. this._captureActiveMeshesEvaluationTime = value;
  109808. if (value) {
  109809. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  109810. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  109811. _this._activeMeshesEvaluationTime.beginMonitoring();
  109812. });
  109813. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  109814. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  109815. _this._activeMeshesEvaluationTime.endMonitoring();
  109816. });
  109817. }
  109818. else {
  109819. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109820. this._onBeforeActiveMeshesEvaluationObserver = null;
  109821. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109822. this._onAfterActiveMeshesEvaluationObserver = null;
  109823. }
  109824. },
  109825. enumerable: true,
  109826. configurable: true
  109827. });
  109828. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  109829. /**
  109830. * Gets the perf counter used for render targets render time
  109831. */
  109832. get: function () {
  109833. return this._renderTargetsRenderTime;
  109834. },
  109835. enumerable: true,
  109836. configurable: true
  109837. });
  109838. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  109839. /**
  109840. * Gets the render targets render time capture status
  109841. */
  109842. get: function () {
  109843. return this._captureRenderTargetsRenderTime;
  109844. },
  109845. /**
  109846. * Enable or disable the render targets render time capture
  109847. */
  109848. set: function (value) {
  109849. var _this = this;
  109850. if (value === this._captureRenderTargetsRenderTime) {
  109851. return;
  109852. }
  109853. this._captureRenderTargetsRenderTime = value;
  109854. if (value) {
  109855. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  109856. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  109857. _this._renderTargetsRenderTime.beginMonitoring();
  109858. });
  109859. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  109860. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  109861. _this._renderTargetsRenderTime.endMonitoring(false);
  109862. });
  109863. }
  109864. else {
  109865. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109866. this._onBeforeRenderTargetsRenderObserver = null;
  109867. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109868. this._onAfterRenderTargetsRenderObserver = null;
  109869. }
  109870. },
  109871. enumerable: true,
  109872. configurable: true
  109873. });
  109874. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  109875. /**
  109876. * Gets the perf counter used for particles render time
  109877. */
  109878. get: function () {
  109879. return this._particlesRenderTime;
  109880. },
  109881. enumerable: true,
  109882. configurable: true
  109883. });
  109884. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  109885. /**
  109886. * Gets the particles render time capture status
  109887. */
  109888. get: function () {
  109889. return this._captureParticlesRenderTime;
  109890. },
  109891. /**
  109892. * Enable or disable the particles render time capture
  109893. */
  109894. set: function (value) {
  109895. var _this = this;
  109896. if (value === this._captureParticlesRenderTime) {
  109897. return;
  109898. }
  109899. this._captureParticlesRenderTime = value;
  109900. if (value) {
  109901. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  109902. BABYLON.Tools.StartPerformanceCounter("Particles");
  109903. _this._particlesRenderTime.beginMonitoring();
  109904. });
  109905. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  109906. BABYLON.Tools.EndPerformanceCounter("Particles");
  109907. _this._particlesRenderTime.endMonitoring(false);
  109908. });
  109909. }
  109910. else {
  109911. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109912. this._onBeforeParticlesRenderingObserver = null;
  109913. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109914. this._onAfterParticlesRenderingObserver = null;
  109915. }
  109916. },
  109917. enumerable: true,
  109918. configurable: true
  109919. });
  109920. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  109921. /**
  109922. * Gets the perf counter used for sprites render time
  109923. */
  109924. get: function () {
  109925. return this._spritesRenderTime;
  109926. },
  109927. enumerable: true,
  109928. configurable: true
  109929. });
  109930. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  109931. /**
  109932. * Gets the sprites render time capture status
  109933. */
  109934. get: function () {
  109935. return this._captureSpritesRenderTime;
  109936. },
  109937. /**
  109938. * Enable or disable the sprites render time capture
  109939. */
  109940. set: function (value) {
  109941. var _this = this;
  109942. if (value === this._captureSpritesRenderTime) {
  109943. return;
  109944. }
  109945. this._captureSpritesRenderTime = value;
  109946. if (!this.scene.spriteManagers) {
  109947. return;
  109948. }
  109949. if (value) {
  109950. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  109951. BABYLON.Tools.StartPerformanceCounter("Sprites");
  109952. _this._spritesRenderTime.beginMonitoring();
  109953. });
  109954. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  109955. BABYLON.Tools.EndPerformanceCounter("Sprites");
  109956. _this._spritesRenderTime.endMonitoring(false);
  109957. });
  109958. }
  109959. else {
  109960. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109961. this._onBeforeSpritesRenderingObserver = null;
  109962. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109963. this._onAfterSpritesRenderingObserver = null;
  109964. }
  109965. },
  109966. enumerable: true,
  109967. configurable: true
  109968. });
  109969. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  109970. /**
  109971. * Gets the perf counter used for physics time
  109972. */
  109973. get: function () {
  109974. return this._physicsTime;
  109975. },
  109976. enumerable: true,
  109977. configurable: true
  109978. });
  109979. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  109980. /**
  109981. * Gets the physics time capture status
  109982. */
  109983. get: function () {
  109984. return this._capturePhysicsTime;
  109985. },
  109986. /**
  109987. * Enable or disable the physics time capture
  109988. */
  109989. set: function (value) {
  109990. var _this = this;
  109991. if (value === this._capturePhysicsTime) {
  109992. return;
  109993. }
  109994. if (!this.scene.onBeforePhysicsObservable) {
  109995. return;
  109996. }
  109997. this._capturePhysicsTime = value;
  109998. if (value) {
  109999. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  110000. BABYLON.Tools.StartPerformanceCounter("Physics");
  110001. _this._physicsTime.beginMonitoring();
  110002. });
  110003. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  110004. BABYLON.Tools.EndPerformanceCounter("Physics");
  110005. _this._physicsTime.endMonitoring();
  110006. });
  110007. }
  110008. else {
  110009. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110010. this._onBeforePhysicsObserver = null;
  110011. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110012. this._onAfterPhysicsObserver = null;
  110013. }
  110014. },
  110015. enumerable: true,
  110016. configurable: true
  110017. });
  110018. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  110019. /**
  110020. * Gets the perf counter used for animations time
  110021. */
  110022. get: function () {
  110023. return this._animationsTime;
  110024. },
  110025. enumerable: true,
  110026. configurable: true
  110027. });
  110028. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  110029. /**
  110030. * Gets the animations time capture status
  110031. */
  110032. get: function () {
  110033. return this._captureAnimationsTime;
  110034. },
  110035. /**
  110036. * Enable or disable the animations time capture
  110037. */
  110038. set: function (value) {
  110039. var _this = this;
  110040. if (value === this._captureAnimationsTime) {
  110041. return;
  110042. }
  110043. this._captureAnimationsTime = value;
  110044. if (value) {
  110045. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  110046. _this._animationsTime.endMonitoring();
  110047. });
  110048. }
  110049. else {
  110050. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110051. this._onAfterAnimationsObserver = null;
  110052. }
  110053. },
  110054. enumerable: true,
  110055. configurable: true
  110056. });
  110057. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  110058. /**
  110059. * Gets the perf counter used for frame time capture
  110060. */
  110061. get: function () {
  110062. return this._frameTime;
  110063. },
  110064. enumerable: true,
  110065. configurable: true
  110066. });
  110067. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  110068. /**
  110069. * Gets the frame time capture status
  110070. */
  110071. get: function () {
  110072. return this._captureFrameTime;
  110073. },
  110074. /**
  110075. * Enable or disable the frame time capture
  110076. */
  110077. set: function (value) {
  110078. this._captureFrameTime = value;
  110079. },
  110080. enumerable: true,
  110081. configurable: true
  110082. });
  110083. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  110084. /**
  110085. * Gets the perf counter used for inter-frames time capture
  110086. */
  110087. get: function () {
  110088. return this._interFrameTime;
  110089. },
  110090. enumerable: true,
  110091. configurable: true
  110092. });
  110093. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  110094. /**
  110095. * Gets the inter-frames time capture status
  110096. */
  110097. get: function () {
  110098. return this._captureInterFrameTime;
  110099. },
  110100. /**
  110101. * Enable or disable the inter-frames time capture
  110102. */
  110103. set: function (value) {
  110104. this._captureInterFrameTime = value;
  110105. },
  110106. enumerable: true,
  110107. configurable: true
  110108. });
  110109. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  110110. /**
  110111. * Gets the perf counter used for render time capture
  110112. */
  110113. get: function () {
  110114. return this._renderTime;
  110115. },
  110116. enumerable: true,
  110117. configurable: true
  110118. });
  110119. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  110120. /**
  110121. * Gets the render time capture status
  110122. */
  110123. get: function () {
  110124. return this._captureRenderTime;
  110125. },
  110126. /**
  110127. * Enable or disable the render time capture
  110128. */
  110129. set: function (value) {
  110130. var _this = this;
  110131. if (value === this._captureRenderTime) {
  110132. return;
  110133. }
  110134. this._captureRenderTime = value;
  110135. if (value) {
  110136. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  110137. _this._renderTime.beginMonitoring();
  110138. BABYLON.Tools.StartPerformanceCounter("Main render");
  110139. });
  110140. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  110141. _this._renderTime.endMonitoring(false);
  110142. BABYLON.Tools.EndPerformanceCounter("Main render");
  110143. });
  110144. }
  110145. else {
  110146. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110147. this._onBeforeDrawPhaseObserver = null;
  110148. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110149. this._onAfterDrawPhaseObserver = null;
  110150. }
  110151. },
  110152. enumerable: true,
  110153. configurable: true
  110154. });
  110155. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  110156. /**
  110157. * Gets the perf counter used for camera render time capture
  110158. */
  110159. get: function () {
  110160. return this._cameraRenderTime;
  110161. },
  110162. enumerable: true,
  110163. configurable: true
  110164. });
  110165. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  110166. /**
  110167. * Gets the camera render time capture status
  110168. */
  110169. get: function () {
  110170. return this._captureCameraRenderTime;
  110171. },
  110172. /**
  110173. * Enable or disable the camera render time capture
  110174. */
  110175. set: function (value) {
  110176. var _this = this;
  110177. if (value === this._captureCameraRenderTime) {
  110178. return;
  110179. }
  110180. this._captureCameraRenderTime = value;
  110181. if (value) {
  110182. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  110183. _this._cameraRenderTime.beginMonitoring();
  110184. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  110185. });
  110186. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  110187. _this._cameraRenderTime.endMonitoring(false);
  110188. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  110189. });
  110190. }
  110191. else {
  110192. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110193. this._onBeforeCameraRenderObserver = null;
  110194. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110195. this._onAfterCameraRenderObserver = null;
  110196. }
  110197. },
  110198. enumerable: true,
  110199. configurable: true
  110200. });
  110201. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  110202. /**
  110203. * Gets the perf counter used for draw calls
  110204. */
  110205. get: function () {
  110206. return this.scene.getEngine()._drawCalls;
  110207. },
  110208. enumerable: true,
  110209. configurable: true
  110210. });
  110211. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  110212. /**
  110213. * Gets the perf counter used for texture collisions
  110214. */
  110215. get: function () {
  110216. return this.scene.getEngine()._textureCollisions;
  110217. },
  110218. enumerable: true,
  110219. configurable: true
  110220. });
  110221. /**
  110222. * Dispose and release associated resources.
  110223. */
  110224. SceneInstrumentation.prototype.dispose = function () {
  110225. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110226. this._onAfterRenderObserver = null;
  110227. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110228. this._onBeforeActiveMeshesEvaluationObserver = null;
  110229. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110230. this._onAfterActiveMeshesEvaluationObserver = null;
  110231. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110232. this._onBeforeRenderTargetsRenderObserver = null;
  110233. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110234. this._onAfterRenderTargetsRenderObserver = null;
  110235. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  110236. this._onBeforeAnimationsObserver = null;
  110237. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110238. this._onBeforeParticlesRenderingObserver = null;
  110239. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110240. this._onAfterParticlesRenderingObserver = null;
  110241. if (this._onBeforeSpritesRenderingObserver) {
  110242. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110243. this._onBeforeSpritesRenderingObserver = null;
  110244. }
  110245. if (this._onAfterSpritesRenderingObserver) {
  110246. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110247. this._onAfterSpritesRenderingObserver = null;
  110248. }
  110249. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110250. this._onBeforeDrawPhaseObserver = null;
  110251. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110252. this._onAfterDrawPhaseObserver = null;
  110253. if (this._onBeforePhysicsObserver) {
  110254. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110255. this._onBeforePhysicsObserver = null;
  110256. }
  110257. if (this._onAfterPhysicsObserver) {
  110258. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110259. this._onAfterPhysicsObserver = null;
  110260. }
  110261. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110262. this._onAfterAnimationsObserver = null;
  110263. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110264. this._onBeforeCameraRenderObserver = null;
  110265. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110266. this._onAfterCameraRenderObserver = null;
  110267. this.scene = null;
  110268. };
  110269. return SceneInstrumentation;
  110270. }());
  110271. BABYLON.SceneInstrumentation = SceneInstrumentation;
  110272. })(BABYLON || (BABYLON = {}));
  110273. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  110274. var BABYLON;
  110275. (function (BABYLON) {
  110276. /**
  110277. * @hidden
  110278. **/
  110279. var _TimeToken = /** @class */ (function () {
  110280. function _TimeToken() {
  110281. this._timeElapsedQueryEnded = false;
  110282. }
  110283. return _TimeToken;
  110284. }());
  110285. BABYLON._TimeToken = _TimeToken;
  110286. })(BABYLON || (BABYLON = {}));
  110287. //# sourceMappingURL=babylon.timeToken.js.map
  110288. var BABYLON;
  110289. (function (BABYLON) {
  110290. /**
  110291. * Background material defines definition.
  110292. * @hidden Mainly internal Use
  110293. */
  110294. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  110295. __extends(BackgroundMaterialDefines, _super);
  110296. /**
  110297. * Constructor of the defines.
  110298. */
  110299. function BackgroundMaterialDefines() {
  110300. var _this = _super.call(this) || this;
  110301. /**
  110302. * True if the diffuse texture is in use.
  110303. */
  110304. _this.DIFFUSE = false;
  110305. /**
  110306. * The direct UV channel to use.
  110307. */
  110308. _this.DIFFUSEDIRECTUV = 0;
  110309. /**
  110310. * True if the diffuse texture is in gamma space.
  110311. */
  110312. _this.GAMMADIFFUSE = false;
  110313. /**
  110314. * True if the diffuse texture has opacity in the alpha channel.
  110315. */
  110316. _this.DIFFUSEHASALPHA = false;
  110317. /**
  110318. * True if you want the material to fade to transparent at grazing angle.
  110319. */
  110320. _this.OPACITYFRESNEL = false;
  110321. /**
  110322. * True if an extra blur needs to be added in the reflection.
  110323. */
  110324. _this.REFLECTIONBLUR = false;
  110325. /**
  110326. * True if you want the material to fade to reflection at grazing angle.
  110327. */
  110328. _this.REFLECTIONFRESNEL = false;
  110329. /**
  110330. * True if you want the material to falloff as far as you move away from the scene center.
  110331. */
  110332. _this.REFLECTIONFALLOFF = false;
  110333. /**
  110334. * False if the current Webgl implementation does not support the texture lod extension.
  110335. */
  110336. _this.TEXTURELODSUPPORT = false;
  110337. /**
  110338. * True to ensure the data are premultiplied.
  110339. */
  110340. _this.PREMULTIPLYALPHA = false;
  110341. /**
  110342. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  110343. */
  110344. _this.USERGBCOLOR = false;
  110345. /**
  110346. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  110347. * stays aligned with the desired configuration.
  110348. */
  110349. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  110350. /**
  110351. * True to add noise in order to reduce the banding effect.
  110352. */
  110353. _this.NOISE = false;
  110354. /**
  110355. * is the reflection texture in BGR color scheme?
  110356. * Mainly used to solve a bug in ios10 video tag
  110357. */
  110358. _this.REFLECTIONBGR = false;
  110359. _this.IMAGEPROCESSING = false;
  110360. _this.VIGNETTE = false;
  110361. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  110362. _this.VIGNETTEBLENDMODEOPAQUE = false;
  110363. _this.TONEMAPPING = false;
  110364. _this.TONEMAPPING_ACES = false;
  110365. _this.CONTRAST = false;
  110366. _this.COLORCURVES = false;
  110367. _this.COLORGRADING = false;
  110368. _this.COLORGRADING3D = false;
  110369. _this.SAMPLER3DGREENDEPTH = false;
  110370. _this.SAMPLER3DBGRMAP = false;
  110371. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  110372. _this.EXPOSURE = false;
  110373. // Reflection.
  110374. _this.REFLECTION = false;
  110375. _this.REFLECTIONMAP_3D = false;
  110376. _this.REFLECTIONMAP_SPHERICAL = false;
  110377. _this.REFLECTIONMAP_PLANAR = false;
  110378. _this.REFLECTIONMAP_CUBIC = false;
  110379. _this.REFLECTIONMAP_PROJECTION = false;
  110380. _this.REFLECTIONMAP_SKYBOX = false;
  110381. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110382. _this.REFLECTIONMAP_EXPLICIT = false;
  110383. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110384. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110385. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110386. _this.INVERTCUBICMAP = false;
  110387. _this.REFLECTIONMAP_OPPOSITEZ = false;
  110388. _this.LODINREFLECTIONALPHA = false;
  110389. _this.GAMMAREFLECTION = false;
  110390. _this.RGBDREFLECTION = false;
  110391. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  110392. // Default BJS.
  110393. _this.MAINUV1 = false;
  110394. _this.MAINUV2 = false;
  110395. _this.UV1 = false;
  110396. _this.UV2 = false;
  110397. _this.CLIPPLANE = false;
  110398. _this.CLIPPLANE2 = false;
  110399. _this.CLIPPLANE3 = false;
  110400. _this.CLIPPLANE4 = false;
  110401. _this.POINTSIZE = false;
  110402. _this.FOG = false;
  110403. _this.NORMAL = false;
  110404. _this.NUM_BONE_INFLUENCERS = 0;
  110405. _this.BonesPerMesh = 0;
  110406. _this.INSTANCES = false;
  110407. _this.SHADOWFLOAT = false;
  110408. _this.rebuild();
  110409. return _this;
  110410. }
  110411. return BackgroundMaterialDefines;
  110412. }(BABYLON.MaterialDefines));
  110413. /**
  110414. * Background material used to create an efficient environement around your scene.
  110415. */
  110416. var BackgroundMaterial = /** @class */ (function (_super) {
  110417. __extends(BackgroundMaterial, _super);
  110418. /**
  110419. * Instantiates a Background Material in the given scene
  110420. * @param name The friendly name of the material
  110421. * @param scene The scene to add the material to
  110422. */
  110423. function BackgroundMaterial(name, scene) {
  110424. var _this = _super.call(this, name, scene) || this;
  110425. /**
  110426. * Key light Color (multiply against the environement texture)
  110427. */
  110428. _this.primaryColor = BABYLON.Color3.White();
  110429. _this._primaryColorShadowLevel = 0;
  110430. _this._primaryColorHighlightLevel = 0;
  110431. /**
  110432. * Reflection Texture used in the material.
  110433. * Should be author in a specific way for the best result (refer to the documentation).
  110434. */
  110435. _this.reflectionTexture = null;
  110436. /**
  110437. * Reflection Texture level of blur.
  110438. *
  110439. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  110440. * texture twice.
  110441. */
  110442. _this.reflectionBlur = 0;
  110443. /**
  110444. * Diffuse Texture used in the material.
  110445. * Should be author in a specific way for the best result (refer to the documentation).
  110446. */
  110447. _this.diffuseTexture = null;
  110448. _this._shadowLights = null;
  110449. /**
  110450. * Specify the list of lights casting shadow on the material.
  110451. * All scene shadow lights will be included if null.
  110452. */
  110453. _this.shadowLights = null;
  110454. /**
  110455. * Helps adjusting the shadow to a softer level if required.
  110456. * 0 means black shadows and 1 means no shadows.
  110457. */
  110458. _this.shadowLevel = 0;
  110459. /**
  110460. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  110461. * It is usually zero but might be interesting to modify according to your setup.
  110462. */
  110463. _this.sceneCenter = BABYLON.Vector3.Zero();
  110464. /**
  110465. * This helps specifying that the material is falling off to the sky box at grazing angle.
  110466. * This helps ensuring a nice transition when the camera goes under the ground.
  110467. */
  110468. _this.opacityFresnel = true;
  110469. /**
  110470. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  110471. * This helps adding a mirror texture on the ground.
  110472. */
  110473. _this.reflectionFresnel = false;
  110474. /**
  110475. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  110476. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  110477. */
  110478. _this.reflectionFalloffDistance = 0.0;
  110479. /**
  110480. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  110481. */
  110482. _this.reflectionAmount = 1.0;
  110483. /**
  110484. * This specifies the weight of the reflection at grazing angle.
  110485. */
  110486. _this.reflectionReflectance0 = 0.05;
  110487. /**
  110488. * This specifies the weight of the reflection at a perpendicular point of view.
  110489. */
  110490. _this.reflectionReflectance90 = 0.5;
  110491. /**
  110492. * Helps to directly use the maps channels instead of their level.
  110493. */
  110494. _this.useRGBColor = true;
  110495. /**
  110496. * This helps reducing the banding effect that could occur on the background.
  110497. */
  110498. _this.enableNoise = false;
  110499. _this._fovMultiplier = 1.0;
  110500. /**
  110501. * Enable the FOV adjustment feature controlled by fovMultiplier.
  110502. */
  110503. _this.useEquirectangularFOV = false;
  110504. _this._maxSimultaneousLights = 4;
  110505. /**
  110506. * Number of Simultaneous lights allowed on the material.
  110507. */
  110508. _this.maxSimultaneousLights = 4;
  110509. /**
  110510. * Keep track of the image processing observer to allow dispose and replace.
  110511. */
  110512. _this._imageProcessingObserver = null;
  110513. /**
  110514. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  110515. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  110516. */
  110517. _this.switchToBGR = false;
  110518. // Temp values kept as cache in the material.
  110519. _this._renderTargets = new BABYLON.SmartArray(16);
  110520. _this._reflectionControls = BABYLON.Vector4.Zero();
  110521. _this._white = BABYLON.Color3.White();
  110522. _this._primaryShadowColor = BABYLON.Color3.Black();
  110523. _this._primaryHighlightColor = BABYLON.Color3.Black();
  110524. // Setup the default processing configuration to the scene.
  110525. _this._attachImageProcessingConfiguration(null);
  110526. _this.getRenderTargetTextures = function () {
  110527. _this._renderTargets.reset();
  110528. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  110529. _this._renderTargets.push(_this._diffuseTexture);
  110530. }
  110531. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  110532. _this._renderTargets.push(_this._reflectionTexture);
  110533. }
  110534. return _this._renderTargets;
  110535. };
  110536. return _this;
  110537. }
  110538. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  110539. /**
  110540. * Experimental Internal Use Only.
  110541. *
  110542. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  110543. * This acts as a helper to set the primary color to a more "human friendly" value.
  110544. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  110545. * output color as close as possible from the chosen value.
  110546. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  110547. * part of lighting setup.)
  110548. */
  110549. get: function () {
  110550. return this.__perceptualColor;
  110551. },
  110552. set: function (value) {
  110553. this.__perceptualColor = value;
  110554. this._computePrimaryColorFromPerceptualColor();
  110555. this._markAllSubMeshesAsLightsDirty();
  110556. },
  110557. enumerable: true,
  110558. configurable: true
  110559. });
  110560. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  110561. /**
  110562. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  110563. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  110564. */
  110565. get: function () {
  110566. return this._primaryColorShadowLevel;
  110567. },
  110568. set: function (value) {
  110569. this._primaryColorShadowLevel = value;
  110570. this._computePrimaryColors();
  110571. this._markAllSubMeshesAsLightsDirty();
  110572. },
  110573. enumerable: true,
  110574. configurable: true
  110575. });
  110576. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  110577. /**
  110578. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  110579. * The primary color is used at the level chosen to define what the white area would look.
  110580. */
  110581. get: function () {
  110582. return this._primaryColorHighlightLevel;
  110583. },
  110584. set: function (value) {
  110585. this._primaryColorHighlightLevel = value;
  110586. this._computePrimaryColors();
  110587. this._markAllSubMeshesAsLightsDirty();
  110588. },
  110589. enumerable: true,
  110590. configurable: true
  110591. });
  110592. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  110593. /**
  110594. * Sets the reflection reflectance fresnel values according to the default standard
  110595. * empirically know to work well :-)
  110596. */
  110597. set: function (value) {
  110598. var reflectionWeight = value;
  110599. if (reflectionWeight < 0.5) {
  110600. reflectionWeight = reflectionWeight * 2.0;
  110601. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  110602. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  110603. }
  110604. else {
  110605. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  110606. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  110607. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  110608. }
  110609. },
  110610. enumerable: true,
  110611. configurable: true
  110612. });
  110613. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  110614. /**
  110615. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  110616. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  110617. * Recommended to be keep at 1.0 except for special cases.
  110618. */
  110619. get: function () {
  110620. return this._fovMultiplier;
  110621. },
  110622. set: function (value) {
  110623. if (isNaN(value)) {
  110624. value = 1.0;
  110625. }
  110626. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  110627. },
  110628. enumerable: true,
  110629. configurable: true
  110630. });
  110631. /**
  110632. * Attaches a new image processing configuration to the PBR Material.
  110633. * @param configuration (if null the scene configuration will be use)
  110634. */
  110635. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  110636. var _this = this;
  110637. if (configuration === this._imageProcessingConfiguration) {
  110638. return;
  110639. }
  110640. // Detaches observer.
  110641. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110642. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110643. }
  110644. // Pick the scene configuration if needed.
  110645. if (!configuration) {
  110646. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  110647. }
  110648. else {
  110649. this._imageProcessingConfiguration = configuration;
  110650. }
  110651. // Attaches observer.
  110652. if (this._imageProcessingConfiguration) {
  110653. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  110654. _this._computePrimaryColorFromPerceptualColor();
  110655. _this._markAllSubMeshesAsImageProcessingDirty();
  110656. });
  110657. }
  110658. };
  110659. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  110660. /**
  110661. * Gets the image processing configuration used either in this material.
  110662. */
  110663. get: function () {
  110664. return this._imageProcessingConfiguration;
  110665. },
  110666. /**
  110667. * Sets the Default image processing configuration used either in the this material.
  110668. *
  110669. * If sets to null, the scene one is in use.
  110670. */
  110671. set: function (value) {
  110672. this._attachImageProcessingConfiguration(value);
  110673. // Ensure the effect will be rebuilt.
  110674. this._markAllSubMeshesAsTexturesDirty();
  110675. },
  110676. enumerable: true,
  110677. configurable: true
  110678. });
  110679. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  110680. /**
  110681. * Gets wether the color curves effect is enabled.
  110682. */
  110683. get: function () {
  110684. return this.imageProcessingConfiguration.colorCurvesEnabled;
  110685. },
  110686. /**
  110687. * Sets wether the color curves effect is enabled.
  110688. */
  110689. set: function (value) {
  110690. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  110691. },
  110692. enumerable: true,
  110693. configurable: true
  110694. });
  110695. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  110696. /**
  110697. * Gets wether the color grading effect is enabled.
  110698. */
  110699. get: function () {
  110700. return this.imageProcessingConfiguration.colorGradingEnabled;
  110701. },
  110702. /**
  110703. * Gets wether the color grading effect is enabled.
  110704. */
  110705. set: function (value) {
  110706. this.imageProcessingConfiguration.colorGradingEnabled = value;
  110707. },
  110708. enumerable: true,
  110709. configurable: true
  110710. });
  110711. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  110712. /**
  110713. * Gets wether tonemapping is enabled or not.
  110714. */
  110715. get: function () {
  110716. return this._imageProcessingConfiguration.toneMappingEnabled;
  110717. },
  110718. /**
  110719. * Sets wether tonemapping is enabled or not
  110720. */
  110721. set: function (value) {
  110722. this._imageProcessingConfiguration.toneMappingEnabled = value;
  110723. },
  110724. enumerable: true,
  110725. configurable: true
  110726. });
  110727. ;
  110728. ;
  110729. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  110730. /**
  110731. * The camera exposure used on this material.
  110732. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110733. * This corresponds to a photographic exposure.
  110734. */
  110735. get: function () {
  110736. return this._imageProcessingConfiguration.exposure;
  110737. },
  110738. /**
  110739. * The camera exposure used on this material.
  110740. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110741. * This corresponds to a photographic exposure.
  110742. */
  110743. set: function (value) {
  110744. this._imageProcessingConfiguration.exposure = value;
  110745. },
  110746. enumerable: true,
  110747. configurable: true
  110748. });
  110749. ;
  110750. ;
  110751. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  110752. /**
  110753. * Gets The camera contrast used on this material.
  110754. */
  110755. get: function () {
  110756. return this._imageProcessingConfiguration.contrast;
  110757. },
  110758. /**
  110759. * Sets The camera contrast used on this material.
  110760. */
  110761. set: function (value) {
  110762. this._imageProcessingConfiguration.contrast = value;
  110763. },
  110764. enumerable: true,
  110765. configurable: true
  110766. });
  110767. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  110768. /**
  110769. * Gets the Color Grading 2D Lookup Texture.
  110770. */
  110771. get: function () {
  110772. return this._imageProcessingConfiguration.colorGradingTexture;
  110773. },
  110774. /**
  110775. * Sets the Color Grading 2D Lookup Texture.
  110776. */
  110777. set: function (value) {
  110778. this.imageProcessingConfiguration.colorGradingTexture = value;
  110779. },
  110780. enumerable: true,
  110781. configurable: true
  110782. });
  110783. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  110784. /**
  110785. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110786. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110787. * 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;
  110788. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110789. */
  110790. get: function () {
  110791. return this.imageProcessingConfiguration.colorCurves;
  110792. },
  110793. /**
  110794. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110795. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110796. * 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;
  110797. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110798. */
  110799. set: function (value) {
  110800. this.imageProcessingConfiguration.colorCurves = value;
  110801. },
  110802. enumerable: true,
  110803. configurable: true
  110804. });
  110805. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  110806. /**
  110807. * Gets a boolean indicating that current material needs to register RTT
  110808. */
  110809. get: function () {
  110810. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110811. return true;
  110812. }
  110813. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110814. return true;
  110815. }
  110816. return false;
  110817. },
  110818. enumerable: true,
  110819. configurable: true
  110820. });
  110821. /**
  110822. * The entire material has been created in order to prevent overdraw.
  110823. * @returns false
  110824. */
  110825. BackgroundMaterial.prototype.needAlphaTesting = function () {
  110826. return true;
  110827. };
  110828. /**
  110829. * The entire material has been created in order to prevent overdraw.
  110830. * @returns true if blending is enable
  110831. */
  110832. BackgroundMaterial.prototype.needAlphaBlending = function () {
  110833. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  110834. };
  110835. /**
  110836. * Checks wether the material is ready to be rendered for a given mesh.
  110837. * @param mesh The mesh to render
  110838. * @param subMesh The submesh to check against
  110839. * @param useInstances Specify wether or not the material is used with instances
  110840. * @returns true if all the dependencies are ready (Textures, Effects...)
  110841. */
  110842. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  110843. var _this = this;
  110844. if (useInstances === void 0) { useInstances = false; }
  110845. if (subMesh.effect && this.isFrozen) {
  110846. if (this._wasPreviouslyReady) {
  110847. return true;
  110848. }
  110849. }
  110850. if (!subMesh._materialDefines) {
  110851. subMesh._materialDefines = new BackgroundMaterialDefines();
  110852. }
  110853. var scene = this.getScene();
  110854. var defines = subMesh._materialDefines;
  110855. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  110856. if (defines._renderId === scene.getRenderId()) {
  110857. return true;
  110858. }
  110859. }
  110860. var engine = scene.getEngine();
  110861. // Lights
  110862. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  110863. defines._needNormals = true;
  110864. // Textures
  110865. if (defines._areTexturesDirty) {
  110866. defines._needUVs = false;
  110867. if (scene.texturesEnabled) {
  110868. if (scene.getEngine().getCaps().textureLOD) {
  110869. defines.TEXTURELODSUPPORT = true;
  110870. }
  110871. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110872. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  110873. return false;
  110874. }
  110875. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  110876. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  110877. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  110878. defines.OPACITYFRESNEL = this._opacityFresnel;
  110879. }
  110880. else {
  110881. defines.DIFFUSE = false;
  110882. defines.DIFFUSEHASALPHA = false;
  110883. defines.GAMMADIFFUSE = false;
  110884. defines.OPACITYFRESNEL = false;
  110885. }
  110886. var reflectionTexture = this._reflectionTexture;
  110887. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110888. if (!reflectionTexture.isReadyOrNotBlocking()) {
  110889. return false;
  110890. }
  110891. defines.REFLECTION = true;
  110892. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  110893. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  110894. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  110895. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  110896. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  110897. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  110898. defines.REFLECTIONBGR = this.switchToBGR;
  110899. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  110900. defines.INVERTCUBICMAP = true;
  110901. }
  110902. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  110903. switch (reflectionTexture.coordinatesMode) {
  110904. case BABYLON.Texture.EXPLICIT_MODE:
  110905. defines.REFLECTIONMAP_EXPLICIT = true;
  110906. break;
  110907. case BABYLON.Texture.PLANAR_MODE:
  110908. defines.REFLECTIONMAP_PLANAR = true;
  110909. break;
  110910. case BABYLON.Texture.PROJECTION_MODE:
  110911. defines.REFLECTIONMAP_PROJECTION = true;
  110912. break;
  110913. case BABYLON.Texture.SKYBOX_MODE:
  110914. defines.REFLECTIONMAP_SKYBOX = true;
  110915. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  110916. break;
  110917. case BABYLON.Texture.SPHERICAL_MODE:
  110918. defines.REFLECTIONMAP_SPHERICAL = true;
  110919. break;
  110920. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  110921. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  110922. break;
  110923. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  110924. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  110925. break;
  110926. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  110927. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  110928. break;
  110929. case BABYLON.Texture.CUBIC_MODE:
  110930. case BABYLON.Texture.INVCUBIC_MODE:
  110931. default:
  110932. defines.REFLECTIONMAP_CUBIC = true;
  110933. break;
  110934. }
  110935. if (this.reflectionFresnel) {
  110936. defines.REFLECTIONFRESNEL = true;
  110937. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  110938. this._reflectionControls.x = this.reflectionAmount;
  110939. this._reflectionControls.y = this.reflectionReflectance0;
  110940. this._reflectionControls.z = this.reflectionReflectance90;
  110941. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  110942. }
  110943. else {
  110944. defines.REFLECTIONFRESNEL = false;
  110945. defines.REFLECTIONFALLOFF = false;
  110946. }
  110947. }
  110948. else {
  110949. defines.REFLECTION = false;
  110950. defines.REFLECTIONFRESNEL = false;
  110951. defines.REFLECTIONFALLOFF = false;
  110952. defines.REFLECTIONBLUR = false;
  110953. defines.REFLECTIONMAP_3D = false;
  110954. defines.REFLECTIONMAP_SPHERICAL = false;
  110955. defines.REFLECTIONMAP_PLANAR = false;
  110956. defines.REFLECTIONMAP_CUBIC = false;
  110957. defines.REFLECTIONMAP_PROJECTION = false;
  110958. defines.REFLECTIONMAP_SKYBOX = false;
  110959. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110960. defines.REFLECTIONMAP_EXPLICIT = false;
  110961. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110962. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110963. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110964. defines.INVERTCUBICMAP = false;
  110965. defines.REFLECTIONMAP_OPPOSITEZ = false;
  110966. defines.LODINREFLECTIONALPHA = false;
  110967. defines.GAMMAREFLECTION = false;
  110968. defines.RGBDREFLECTION = false;
  110969. }
  110970. }
  110971. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  110972. defines.USERGBCOLOR = this._useRGBColor;
  110973. defines.NOISE = this._enableNoise;
  110974. }
  110975. if (defines._areLightsDirty) {
  110976. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  110977. }
  110978. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  110979. if (!this._imageProcessingConfiguration.isReady()) {
  110980. return false;
  110981. }
  110982. this._imageProcessingConfiguration.prepareDefines(defines);
  110983. }
  110984. // Misc.
  110985. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  110986. // Values that need to be evaluated on every frame
  110987. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  110988. // Attribs
  110989. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  110990. if (mesh) {
  110991. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  110992. mesh.createNormals(true);
  110993. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  110994. }
  110995. }
  110996. }
  110997. // Get correct effect
  110998. if (defines.isDirty) {
  110999. defines.markAsProcessed();
  111000. scene.resetCachedMaterial();
  111001. // Fallbacks
  111002. var fallbacks = new BABYLON.EffectFallbacks();
  111003. if (defines.FOG) {
  111004. fallbacks.addFallback(0, "FOG");
  111005. }
  111006. if (defines.POINTSIZE) {
  111007. fallbacks.addFallback(1, "POINTSIZE");
  111008. }
  111009. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  111010. if (defines.NUM_BONE_INFLUENCERS > 0) {
  111011. fallbacks.addCPUSkinningFallback(0, mesh);
  111012. }
  111013. //Attributes
  111014. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111015. if (defines.NORMAL) {
  111016. attribs.push(BABYLON.VertexBuffer.NormalKind);
  111017. }
  111018. if (defines.UV1) {
  111019. attribs.push(BABYLON.VertexBuffer.UVKind);
  111020. }
  111021. if (defines.UV2) {
  111022. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111023. }
  111024. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  111025. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  111026. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  111027. "vFogInfos", "vFogColor", "pointSize",
  111028. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  111029. "vPrimaryColor", "vPrimaryColorShadow",
  111030. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  111031. "shadowLevel", "alpha",
  111032. "vBackgroundCenter", "vReflectionControl",
  111033. "vDiffuseInfos", "diffuseMatrix",
  111034. ];
  111035. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  111036. var uniformBuffers = ["Material", "Scene"];
  111037. if (BABYLON.ImageProcessingConfiguration) {
  111038. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  111039. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  111040. }
  111041. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  111042. uniformsNames: uniforms,
  111043. uniformBuffersNames: uniformBuffers,
  111044. samplers: samplers,
  111045. defines: defines,
  111046. maxSimultaneousLights: this._maxSimultaneousLights
  111047. });
  111048. var onCompiled = function (effect) {
  111049. if (_this.onCompiled) {
  111050. _this.onCompiled(effect);
  111051. }
  111052. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  111053. };
  111054. var join = defines.toString();
  111055. subMesh.setEffect(scene.getEngine().createEffect("background", {
  111056. attributes: attribs,
  111057. uniformsNames: uniforms,
  111058. uniformBuffersNames: uniformBuffers,
  111059. samplers: samplers,
  111060. defines: join,
  111061. fallbacks: fallbacks,
  111062. onCompiled: onCompiled,
  111063. onError: this.onError,
  111064. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  111065. }, engine), defines);
  111066. this.buildUniformLayout();
  111067. }
  111068. if (!subMesh.effect || !subMesh.effect.isReady()) {
  111069. return false;
  111070. }
  111071. defines._renderId = scene.getRenderId();
  111072. this._wasPreviouslyReady = true;
  111073. return true;
  111074. };
  111075. /**
  111076. * Compute the primary color according to the chosen perceptual color.
  111077. */
  111078. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  111079. if (!this.__perceptualColor) {
  111080. return;
  111081. }
  111082. this._primaryColor.copyFrom(this.__perceptualColor);
  111083. // Revert gamma space.
  111084. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  111085. // Revert image processing configuration.
  111086. if (this._imageProcessingConfiguration) {
  111087. // Revert Exposure.
  111088. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  111089. }
  111090. this._computePrimaryColors();
  111091. };
  111092. /**
  111093. * Compute the highlights and shadow colors according to their chosen levels.
  111094. */
  111095. BackgroundMaterial.prototype._computePrimaryColors = function () {
  111096. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  111097. return;
  111098. }
  111099. // Find the highlight color based on the configuration.
  111100. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  111101. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  111102. // Find the shadow color based on the configuration.
  111103. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  111104. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  111105. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  111106. };
  111107. /**
  111108. * Build the uniform buffer used in the material.
  111109. */
  111110. BackgroundMaterial.prototype.buildUniformLayout = function () {
  111111. // Order is important !
  111112. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  111113. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  111114. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  111115. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  111116. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  111117. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  111118. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  111119. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  111120. this._uniformBuffer.addUniform("pointSize", 1);
  111121. this._uniformBuffer.addUniform("shadowLevel", 1);
  111122. this._uniformBuffer.addUniform("alpha", 1);
  111123. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  111124. this._uniformBuffer.addUniform("vReflectionControl", 4);
  111125. this._uniformBuffer.create();
  111126. };
  111127. /**
  111128. * Unbind the material.
  111129. */
  111130. BackgroundMaterial.prototype.unbind = function () {
  111131. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111132. this._uniformBuffer.setTexture("diffuseSampler", null);
  111133. }
  111134. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111135. this._uniformBuffer.setTexture("reflectionSampler", null);
  111136. }
  111137. _super.prototype.unbind.call(this);
  111138. };
  111139. /**
  111140. * Bind only the world matrix to the material.
  111141. * @param world The world matrix to bind.
  111142. */
  111143. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  111144. this._activeEffect.setMatrix("world", world);
  111145. };
  111146. /**
  111147. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  111148. * @param world The world matrix to bind.
  111149. * @param subMesh The submesh to bind for.
  111150. */
  111151. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  111152. var scene = this.getScene();
  111153. var defines = subMesh._materialDefines;
  111154. if (!defines) {
  111155. return;
  111156. }
  111157. var effect = subMesh.effect;
  111158. if (!effect) {
  111159. return;
  111160. }
  111161. this._activeEffect = effect;
  111162. // Matrices
  111163. this.bindOnlyWorldMatrix(world);
  111164. // Bones
  111165. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  111166. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  111167. if (mustRebind) {
  111168. this._uniformBuffer.bindToEffect(effect, "Material");
  111169. this.bindViewProjection(effect);
  111170. var reflectionTexture = this._reflectionTexture;
  111171. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  111172. // Texture uniforms
  111173. if (scene.texturesEnabled) {
  111174. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111175. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  111176. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  111177. }
  111178. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111179. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  111180. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  111181. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  111182. }
  111183. }
  111184. if (this.shadowLevel > 0) {
  111185. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  111186. }
  111187. this._uniformBuffer.updateFloat("alpha", this.alpha);
  111188. // Point size
  111189. if (this.pointsCloud) {
  111190. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  111191. }
  111192. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  111193. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  111194. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  111195. }
  111196. else {
  111197. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  111198. }
  111199. }
  111200. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  111201. // Textures
  111202. if (scene.texturesEnabled) {
  111203. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111204. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  111205. }
  111206. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111207. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  111208. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111209. }
  111210. else if (!defines.REFLECTIONBLUR) {
  111211. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111212. }
  111213. else {
  111214. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  111215. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  111216. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  111217. }
  111218. if (defines.REFLECTIONFRESNEL) {
  111219. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  111220. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  111221. }
  111222. }
  111223. }
  111224. // Clip plane
  111225. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  111226. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  111227. }
  111228. if (mustRebind || !this.isFrozen) {
  111229. if (scene.lightsEnabled) {
  111230. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  111231. }
  111232. // View
  111233. this.bindView(effect);
  111234. // Fog
  111235. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  111236. // image processing
  111237. if (this._imageProcessingConfiguration) {
  111238. this._imageProcessingConfiguration.bind(this._activeEffect);
  111239. }
  111240. }
  111241. this._uniformBuffer.update();
  111242. this._afterBind(mesh, this._activeEffect);
  111243. };
  111244. /**
  111245. * Dispose the material.
  111246. * @param forceDisposeEffect Force disposal of the associated effect.
  111247. * @param forceDisposeTextures Force disposal of the associated textures.
  111248. */
  111249. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  111250. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  111251. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  111252. if (forceDisposeTextures) {
  111253. if (this.diffuseTexture) {
  111254. this.diffuseTexture.dispose();
  111255. }
  111256. if (this.reflectionTexture) {
  111257. this.reflectionTexture.dispose();
  111258. }
  111259. }
  111260. this._renderTargets.dispose();
  111261. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111262. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111263. }
  111264. _super.prototype.dispose.call(this, forceDisposeEffect);
  111265. };
  111266. /**
  111267. * Clones the material.
  111268. * @param name The cloned name.
  111269. * @returns The cloned material.
  111270. */
  111271. BackgroundMaterial.prototype.clone = function (name) {
  111272. var _this = this;
  111273. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  111274. };
  111275. /**
  111276. * Serializes the current material to its JSON representation.
  111277. * @returns The JSON representation.
  111278. */
  111279. BackgroundMaterial.prototype.serialize = function () {
  111280. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111281. serializationObject.customType = "BABYLON.BackgroundMaterial";
  111282. return serializationObject;
  111283. };
  111284. /**
  111285. * Gets the class name of the material
  111286. * @returns "BackgroundMaterial"
  111287. */
  111288. BackgroundMaterial.prototype.getClassName = function () {
  111289. return "BackgroundMaterial";
  111290. };
  111291. /**
  111292. * Parse a JSON input to create back a background material.
  111293. * @param source The JSON data to parse
  111294. * @param scene The scene to create the parsed material in
  111295. * @param rootUrl The root url of the assets the material depends upon
  111296. * @returns the instantiated BackgroundMaterial.
  111297. */
  111298. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  111299. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  111300. };
  111301. /**
  111302. * Standard reflectance value at parallel view angle.
  111303. */
  111304. BackgroundMaterial.StandardReflectance0 = 0.05;
  111305. /**
  111306. * Standard reflectance value at grazing angle.
  111307. */
  111308. BackgroundMaterial.StandardReflectance90 = 0.5;
  111309. __decorate([
  111310. BABYLON.serializeAsColor3()
  111311. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  111312. __decorate([
  111313. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111314. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  111315. __decorate([
  111316. BABYLON.serializeAsColor3()
  111317. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  111318. __decorate([
  111319. BABYLON.serialize()
  111320. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  111321. __decorate([
  111322. BABYLON.serialize()
  111323. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  111324. __decorate([
  111325. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111326. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  111327. __decorate([
  111328. BABYLON.serializeAsTexture()
  111329. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  111330. __decorate([
  111331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111332. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  111333. __decorate([
  111334. BABYLON.serialize()
  111335. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  111336. __decorate([
  111337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111338. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  111339. __decorate([
  111340. BABYLON.serializeAsTexture()
  111341. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  111342. __decorate([
  111343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111344. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  111345. __decorate([
  111346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111347. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  111348. __decorate([
  111349. BABYLON.serialize()
  111350. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  111351. __decorate([
  111352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111353. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  111354. __decorate([
  111355. BABYLON.serializeAsVector3()
  111356. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  111357. __decorate([
  111358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111359. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  111360. __decorate([
  111361. BABYLON.serialize()
  111362. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  111363. __decorate([
  111364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111365. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  111366. __decorate([
  111367. BABYLON.serialize()
  111368. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  111369. __decorate([
  111370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111371. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  111372. __decorate([
  111373. BABYLON.serialize()
  111374. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  111375. __decorate([
  111376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111377. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  111378. __decorate([
  111379. BABYLON.serialize()
  111380. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  111381. __decorate([
  111382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111383. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  111384. __decorate([
  111385. BABYLON.serialize()
  111386. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  111387. __decorate([
  111388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111389. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  111390. __decorate([
  111391. BABYLON.serialize()
  111392. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  111393. __decorate([
  111394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111395. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  111396. __decorate([
  111397. BABYLON.serialize()
  111398. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  111399. __decorate([
  111400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111401. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  111402. __decorate([
  111403. BABYLON.serialize()
  111404. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  111405. __decorate([
  111406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111407. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  111408. __decorate([
  111409. BABYLON.serialize()
  111410. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  111411. __decorate([
  111412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111413. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  111414. __decorate([
  111415. BABYLON.serializeAsImageProcessingConfiguration()
  111416. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  111417. return BackgroundMaterial;
  111418. }(BABYLON.PushMaterial));
  111419. BABYLON.BackgroundMaterial = BackgroundMaterial;
  111420. })(BABYLON || (BABYLON = {}));
  111421. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  111422. var __assign = (this && this.__assign) || function () {
  111423. __assign = Object.assign || function(t) {
  111424. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111425. s = arguments[i];
  111426. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111427. t[p] = s[p];
  111428. }
  111429. return t;
  111430. };
  111431. return __assign.apply(this, arguments);
  111432. };
  111433. var BABYLON;
  111434. (function (BABYLON) {
  111435. /**
  111436. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  111437. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  111438. * It also helps with the default setup of your imageProcessing configuration.
  111439. */
  111440. var EnvironmentHelper = /** @class */ (function () {
  111441. /**
  111442. * constructor
  111443. * @param options
  111444. * @param scene The scene to add the material to
  111445. */
  111446. function EnvironmentHelper(options, scene) {
  111447. var _this = this;
  111448. this._errorHandler = function (message, exception) {
  111449. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  111450. };
  111451. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  111452. this._scene = scene;
  111453. this.onErrorObservable = new BABYLON.Observable();
  111454. this._setupBackground();
  111455. this._setupImageProcessing();
  111456. }
  111457. /**
  111458. * Creates the default options for the helper.
  111459. */
  111460. EnvironmentHelper._getDefaultOptions = function () {
  111461. return {
  111462. createGround: true,
  111463. groundSize: 15,
  111464. groundTexture: this._groundTextureCDNUrl,
  111465. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111466. groundOpacity: 0.9,
  111467. enableGroundShadow: true,
  111468. groundShadowLevel: 0.5,
  111469. enableGroundMirror: false,
  111470. groundMirrorSizeRatio: 0.3,
  111471. groundMirrorBlurKernel: 64,
  111472. groundMirrorAmount: 1,
  111473. groundMirrorFresnelWeight: 1,
  111474. groundMirrorFallOffDistance: 0,
  111475. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  111476. groundYBias: 0.00001,
  111477. createSkybox: true,
  111478. skyboxSize: 20,
  111479. skyboxTexture: this._skyboxTextureCDNUrl,
  111480. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111481. backgroundYRotation: 0,
  111482. sizeAuto: true,
  111483. rootPosition: BABYLON.Vector3.Zero(),
  111484. setupImageProcessing: true,
  111485. environmentTexture: this._environmentTextureCDNUrl,
  111486. cameraExposure: 0.8,
  111487. cameraContrast: 1.2,
  111488. toneMappingEnabled: true,
  111489. };
  111490. };
  111491. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  111492. /**
  111493. * Gets the root mesh created by the helper.
  111494. */
  111495. get: function () {
  111496. return this._rootMesh;
  111497. },
  111498. enumerable: true,
  111499. configurable: true
  111500. });
  111501. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  111502. /**
  111503. * Gets the skybox created by the helper.
  111504. */
  111505. get: function () {
  111506. return this._skybox;
  111507. },
  111508. enumerable: true,
  111509. configurable: true
  111510. });
  111511. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  111512. /**
  111513. * Gets the skybox texture created by the helper.
  111514. */
  111515. get: function () {
  111516. return this._skyboxTexture;
  111517. },
  111518. enumerable: true,
  111519. configurable: true
  111520. });
  111521. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  111522. /**
  111523. * Gets the skybox material created by the helper.
  111524. */
  111525. get: function () {
  111526. return this._skyboxMaterial;
  111527. },
  111528. enumerable: true,
  111529. configurable: true
  111530. });
  111531. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  111532. /**
  111533. * Gets the ground mesh created by the helper.
  111534. */
  111535. get: function () {
  111536. return this._ground;
  111537. },
  111538. enumerable: true,
  111539. configurable: true
  111540. });
  111541. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  111542. /**
  111543. * Gets the ground texture created by the helper.
  111544. */
  111545. get: function () {
  111546. return this._groundTexture;
  111547. },
  111548. enumerable: true,
  111549. configurable: true
  111550. });
  111551. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  111552. /**
  111553. * Gets the ground mirror created by the helper.
  111554. */
  111555. get: function () {
  111556. return this._groundMirror;
  111557. },
  111558. enumerable: true,
  111559. configurable: true
  111560. });
  111561. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  111562. /**
  111563. * Gets the ground mirror render list to helps pushing the meshes
  111564. * you wish in the ground reflection.
  111565. */
  111566. get: function () {
  111567. if (this._groundMirror) {
  111568. return this._groundMirror.renderList;
  111569. }
  111570. return null;
  111571. },
  111572. enumerable: true,
  111573. configurable: true
  111574. });
  111575. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  111576. /**
  111577. * Gets the ground material created by the helper.
  111578. */
  111579. get: function () {
  111580. return this._groundMaterial;
  111581. },
  111582. enumerable: true,
  111583. configurable: true
  111584. });
  111585. /**
  111586. * Updates the background according to the new options
  111587. * @param options
  111588. */
  111589. EnvironmentHelper.prototype.updateOptions = function (options) {
  111590. var newOptions = __assign({}, this._options, options);
  111591. if (this._ground && !newOptions.createGround) {
  111592. this._ground.dispose();
  111593. this._ground = null;
  111594. }
  111595. if (this._groundMaterial && !newOptions.createGround) {
  111596. this._groundMaterial.dispose();
  111597. this._groundMaterial = null;
  111598. }
  111599. if (this._groundTexture) {
  111600. if (this._options.groundTexture != newOptions.groundTexture) {
  111601. this._groundTexture.dispose();
  111602. this._groundTexture = null;
  111603. }
  111604. }
  111605. if (this._skybox && !newOptions.createSkybox) {
  111606. this._skybox.dispose();
  111607. this._skybox = null;
  111608. }
  111609. if (this._skyboxMaterial && !newOptions.createSkybox) {
  111610. this._skyboxMaterial.dispose();
  111611. this._skyboxMaterial = null;
  111612. }
  111613. if (this._skyboxTexture) {
  111614. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  111615. this._skyboxTexture.dispose();
  111616. this._skyboxTexture = null;
  111617. }
  111618. }
  111619. if (this._groundMirror && !newOptions.enableGroundMirror) {
  111620. this._groundMirror.dispose();
  111621. this._groundMirror = null;
  111622. }
  111623. if (this._scene.environmentTexture) {
  111624. if (this._options.environmentTexture != newOptions.environmentTexture) {
  111625. this._scene.environmentTexture.dispose();
  111626. }
  111627. }
  111628. this._options = newOptions;
  111629. this._setupBackground();
  111630. this._setupImageProcessing();
  111631. };
  111632. /**
  111633. * Sets the primary color of all the available elements.
  111634. * @param color the main color to affect to the ground and the background
  111635. */
  111636. EnvironmentHelper.prototype.setMainColor = function (color) {
  111637. if (this.groundMaterial) {
  111638. this.groundMaterial.primaryColor = color;
  111639. }
  111640. if (this.skyboxMaterial) {
  111641. this.skyboxMaterial.primaryColor = color;
  111642. }
  111643. if (this.groundMirror) {
  111644. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  111645. }
  111646. };
  111647. /**
  111648. * Setup the image processing according to the specified options.
  111649. */
  111650. EnvironmentHelper.prototype._setupImageProcessing = function () {
  111651. if (this._options.setupImageProcessing) {
  111652. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  111653. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  111654. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  111655. this._setupEnvironmentTexture();
  111656. }
  111657. };
  111658. /**
  111659. * Setup the environment texture according to the specified options.
  111660. */
  111661. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  111662. if (this._scene.environmentTexture) {
  111663. return;
  111664. }
  111665. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  111666. this._scene.environmentTexture = this._options.environmentTexture;
  111667. return;
  111668. }
  111669. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  111670. this._scene.environmentTexture = environmentTexture;
  111671. };
  111672. /**
  111673. * Setup the background according to the specified options.
  111674. */
  111675. EnvironmentHelper.prototype._setupBackground = function () {
  111676. if (!this._rootMesh) {
  111677. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  111678. }
  111679. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  111680. var sceneSize = this._getSceneSize();
  111681. if (this._options.createGround) {
  111682. this._setupGround(sceneSize);
  111683. this._setupGroundMaterial();
  111684. this._setupGroundDiffuseTexture();
  111685. if (this._options.enableGroundMirror) {
  111686. this._setupGroundMirrorTexture(sceneSize);
  111687. }
  111688. this._setupMirrorInGroundMaterial();
  111689. }
  111690. if (this._options.createSkybox) {
  111691. this._setupSkybox(sceneSize);
  111692. this._setupSkyboxMaterial();
  111693. this._setupSkyboxReflectionTexture();
  111694. }
  111695. this._rootMesh.position.x = sceneSize.rootPosition.x;
  111696. this._rootMesh.position.z = sceneSize.rootPosition.z;
  111697. this._rootMesh.position.y = sceneSize.rootPosition.y;
  111698. };
  111699. /**
  111700. * Get the scene sizes according to the setup.
  111701. */
  111702. EnvironmentHelper.prototype._getSceneSize = function () {
  111703. var _this = this;
  111704. var groundSize = this._options.groundSize;
  111705. var skyboxSize = this._options.skyboxSize;
  111706. var rootPosition = this._options.rootPosition;
  111707. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  111708. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111709. }
  111710. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  111711. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  111712. });
  111713. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111714. if (this._options.sizeAuto) {
  111715. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  111716. this._scene.activeCamera.upperRadiusLimit) {
  111717. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  111718. skyboxSize = groundSize;
  111719. }
  111720. var sceneDiagonalLenght = sceneDiagonal.length();
  111721. if (sceneDiagonalLenght > groundSize) {
  111722. groundSize = sceneDiagonalLenght * 2;
  111723. skyboxSize = groundSize;
  111724. }
  111725. // 10 % bigger.
  111726. groundSize *= 1.1;
  111727. skyboxSize *= 1.5;
  111728. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  111729. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  111730. }
  111731. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111732. };
  111733. /**
  111734. * Setup the ground according to the specified options.
  111735. */
  111736. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  111737. var _this = this;
  111738. if (!this._ground || this._ground.isDisposed()) {
  111739. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  111740. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  111741. this._ground.parent = this._rootMesh;
  111742. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  111743. }
  111744. this._ground.receiveShadows = this._options.enableGroundShadow;
  111745. };
  111746. /**
  111747. * Setup the ground material according to the specified options.
  111748. */
  111749. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  111750. if (!this._groundMaterial) {
  111751. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  111752. }
  111753. this._groundMaterial.alpha = this._options.groundOpacity;
  111754. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111755. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  111756. this._groundMaterial.primaryColor = this._options.groundColor;
  111757. this._groundMaterial.useRGBColor = false;
  111758. this._groundMaterial.enableNoise = true;
  111759. if (this._ground) {
  111760. this._ground.material = this._groundMaterial;
  111761. }
  111762. };
  111763. /**
  111764. * Setup the ground diffuse texture according to the specified options.
  111765. */
  111766. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  111767. if (!this._groundMaterial) {
  111768. return;
  111769. }
  111770. if (this._groundTexture) {
  111771. return;
  111772. }
  111773. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  111774. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  111775. return;
  111776. }
  111777. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111778. diffuseTexture.gammaSpace = false;
  111779. diffuseTexture.hasAlpha = true;
  111780. this._groundMaterial.diffuseTexture = diffuseTexture;
  111781. };
  111782. /**
  111783. * Setup the ground mirror texture according to the specified options.
  111784. */
  111785. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  111786. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111787. if (!this._groundMirror) {
  111788. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  111789. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  111790. this._groundMirror.anisotropicFilteringLevel = 1;
  111791. this._groundMirror.wrapU = wrapping;
  111792. this._groundMirror.wrapV = wrapping;
  111793. this._groundMirror.gammaSpace = false;
  111794. if (this._groundMirror.renderList) {
  111795. for (var i = 0; i < this._scene.meshes.length; i++) {
  111796. var mesh = this._scene.meshes[i];
  111797. if (mesh !== this._ground &&
  111798. mesh !== this._skybox &&
  111799. mesh !== this._rootMesh) {
  111800. this._groundMirror.renderList.push(mesh);
  111801. }
  111802. }
  111803. }
  111804. }
  111805. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  111806. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  111807. };
  111808. /**
  111809. * Setup the ground to receive the mirror texture.
  111810. */
  111811. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  111812. if (this._groundMaterial) {
  111813. this._groundMaterial.reflectionTexture = this._groundMirror;
  111814. this._groundMaterial.reflectionFresnel = true;
  111815. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  111816. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  111817. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  111818. }
  111819. };
  111820. /**
  111821. * Setup the skybox according to the specified options.
  111822. */
  111823. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  111824. var _this = this;
  111825. if (!this._skybox || this._skybox.isDisposed()) {
  111826. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  111827. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  111828. }
  111829. this._skybox.parent = this._rootMesh;
  111830. };
  111831. /**
  111832. * Setup the skybox material according to the specified options.
  111833. */
  111834. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  111835. if (!this._skybox) {
  111836. return;
  111837. }
  111838. if (!this._skyboxMaterial) {
  111839. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  111840. }
  111841. this._skyboxMaterial.useRGBColor = false;
  111842. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  111843. this._skyboxMaterial.enableNoise = true;
  111844. this._skybox.material = this._skyboxMaterial;
  111845. };
  111846. /**
  111847. * Setup the skybox reflection texture according to the specified options.
  111848. */
  111849. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  111850. if (!this._skyboxMaterial) {
  111851. return;
  111852. }
  111853. if (this._skyboxTexture) {
  111854. return;
  111855. }
  111856. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  111857. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  111858. return;
  111859. }
  111860. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111861. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111862. this._skyboxTexture.gammaSpace = false;
  111863. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  111864. };
  111865. /**
  111866. * Dispose all the elements created by the Helper.
  111867. */
  111868. EnvironmentHelper.prototype.dispose = function () {
  111869. if (this._groundMaterial) {
  111870. this._groundMaterial.dispose(true, true);
  111871. }
  111872. if (this._skyboxMaterial) {
  111873. this._skyboxMaterial.dispose(true, true);
  111874. }
  111875. this._rootMesh.dispose(false);
  111876. };
  111877. /**
  111878. * Default ground texture URL.
  111879. */
  111880. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  111881. /**
  111882. * Default skybox texture URL.
  111883. */
  111884. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  111885. /**
  111886. * Default environment texture URL.
  111887. */
  111888. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  111889. return EnvironmentHelper;
  111890. }());
  111891. BABYLON.EnvironmentHelper = EnvironmentHelper;
  111892. })(BABYLON || (BABYLON = {}));
  111893. //# sourceMappingURL=babylon.environmentHelper.js.map
  111894. var BABYLON;
  111895. (function (BABYLON) {
  111896. /** Internal class used to store shapes for emitters */
  111897. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  111898. function ParticleSystemSetEmitterCreationOptions() {
  111899. }
  111900. return ParticleSystemSetEmitterCreationOptions;
  111901. }());
  111902. /**
  111903. * Represents a set of particle systems working together to create a specific effect
  111904. */
  111905. var ParticleSystemSet = /** @class */ (function () {
  111906. function ParticleSystemSet() {
  111907. /**
  111908. * Gets the particle system list
  111909. */
  111910. this.systems = new Array();
  111911. }
  111912. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  111913. /**
  111914. * Gets the emitter node used with this set
  111915. */
  111916. get: function () {
  111917. return this._emitterNode;
  111918. },
  111919. enumerable: true,
  111920. configurable: true
  111921. });
  111922. /**
  111923. * Creates a new emitter mesh as a sphere
  111924. * @param options defines the options used to create the sphere
  111925. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  111926. * @param scene defines the hosting scene
  111927. */
  111928. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  111929. if (this._emitterNode) {
  111930. this._emitterNode.dispose();
  111931. }
  111932. this._emitterCreationOptions = {
  111933. kind: "Sphere",
  111934. options: options,
  111935. renderingGroupId: renderingGroupId
  111936. };
  111937. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  111938. emitterMesh.renderingGroupId = renderingGroupId;
  111939. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  111940. material.emissiveColor = options.color;
  111941. emitterMesh.material = material;
  111942. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111943. var system = _a[_i];
  111944. system.emitter = emitterMesh;
  111945. }
  111946. this._emitterNode = emitterMesh;
  111947. };
  111948. /**
  111949. * Starts all particle systems of the set
  111950. * @param emitter defines an optional mesh to use as emitter for the particle systems
  111951. */
  111952. ParticleSystemSet.prototype.start = function (emitter) {
  111953. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111954. var system = _a[_i];
  111955. if (emitter) {
  111956. system.emitter = emitter;
  111957. }
  111958. system.start();
  111959. }
  111960. };
  111961. /**
  111962. * Release all associated resources
  111963. */
  111964. ParticleSystemSet.prototype.dispose = function () {
  111965. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111966. var system = _a[_i];
  111967. system.dispose();
  111968. }
  111969. this.systems = [];
  111970. if (this._emitterNode) {
  111971. this._emitterNode.dispose();
  111972. this._emitterNode = null;
  111973. }
  111974. };
  111975. /**
  111976. * Serialize the set into a JSON compatible object
  111977. * @returns a JSON compatible representation of the set
  111978. */
  111979. ParticleSystemSet.prototype.serialize = function () {
  111980. var result = {};
  111981. result.systems = [];
  111982. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111983. var system = _a[_i];
  111984. result.systems.push(system.serialize());
  111985. }
  111986. if (this._emitterNode) {
  111987. result.emitter = this._emitterCreationOptions;
  111988. }
  111989. return result;
  111990. };
  111991. /**
  111992. * Parse a new ParticleSystemSet from a serialized source
  111993. * @param data defines a JSON compatible representation of the set
  111994. * @param scene defines the hosting scene
  111995. * @param gpu defines if we want GPU particles or CPU particles
  111996. * @returns a new ParticleSystemSet
  111997. */
  111998. ParticleSystemSet.Parse = function (data, scene, gpu) {
  111999. if (gpu === void 0) { gpu = false; }
  112000. var result = new ParticleSystemSet();
  112001. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  112002. scene = scene || BABYLON.Engine.LastCreatedScene;
  112003. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  112004. var system = _a[_i];
  112005. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  112006. }
  112007. if (data.emitter) {
  112008. var options = data.emitter.options;
  112009. switch (data.emitter.kind) {
  112010. case "Sphere":
  112011. result.setEmitterAsSphere({
  112012. diameter: options.diameter,
  112013. segments: options.segments,
  112014. color: BABYLON.Color3.FromArray(options.color)
  112015. }, data.emitter.renderingGroupId, scene);
  112016. break;
  112017. }
  112018. }
  112019. return result;
  112020. };
  112021. return ParticleSystemSet;
  112022. }());
  112023. BABYLON.ParticleSystemSet = ParticleSystemSet;
  112024. })(BABYLON || (BABYLON = {}));
  112025. //# sourceMappingURL=babylon.particleSystemSet.js.map
  112026. var BABYLON;
  112027. (function (BABYLON) {
  112028. /**
  112029. * This class is made for on one-liner static method to help creating particle system set.
  112030. */
  112031. var ParticleHelper = /** @class */ (function () {
  112032. function ParticleHelper() {
  112033. }
  112034. /**
  112035. * Create a default particle system that you can tweak
  112036. * @param emitter defines the emitter to use
  112037. * @param capacity defines the system capacity (default is 500 particles)
  112038. * @param scene defines the hosting scene
  112039. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  112040. * @returns the new Particle system
  112041. */
  112042. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  112043. if (capacity === void 0) { capacity = 500; }
  112044. if (useGPU === void 0) { useGPU = false; }
  112045. var system;
  112046. if (useGPU) {
  112047. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  112048. }
  112049. else {
  112050. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  112051. }
  112052. system.emitter = emitter;
  112053. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  112054. system.createConeEmitter(0.1, Math.PI / 4);
  112055. // Particle color
  112056. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112057. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112058. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  112059. // Particle Size
  112060. system.minSize = 0.1;
  112061. system.maxSize = 0.1;
  112062. // Emission speed
  112063. system.minEmitPower = 2;
  112064. system.maxEmitPower = 2;
  112065. // Update speed
  112066. system.updateSpeed = 1 / 60;
  112067. system.emitRate = 30;
  112068. return system;
  112069. };
  112070. /**
  112071. * This is the main static method (one-liner) of this helper to create different particle systems
  112072. * @param type This string represents the type to the particle system to create
  112073. * @param scene The scene where the particle system should live
  112074. * @param gpu If the system will use gpu
  112075. * @returns the ParticleSystemSet created
  112076. */
  112077. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  112078. if (gpu === void 0) { gpu = false; }
  112079. if (!scene) {
  112080. scene = BABYLON.Engine.LastCreatedScene;
  112081. ;
  112082. }
  112083. var token = {};
  112084. scene._addPendingData(token);
  112085. return new Promise(function (resolve, reject) {
  112086. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  112087. scene._removePendingData(token);
  112088. return reject("Particle system with GPU is not supported.");
  112089. }
  112090. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  112091. scene._removePendingData(token);
  112092. var newData = JSON.parse(data.toString());
  112093. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  112094. }, undefined, undefined, undefined, function (req, exception) {
  112095. scene._removePendingData(token);
  112096. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  112097. });
  112098. });
  112099. };
  112100. /**
  112101. * Static function used to export a particle system to a ParticleSystemSet variable.
  112102. * Please note that the emitter shape is not exported
  112103. * @param system defines the particle systems to export
  112104. */
  112105. ParticleHelper.ExportSet = function (systems) {
  112106. var set = new BABYLON.ParticleSystemSet();
  112107. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  112108. var system = systems_1[_i];
  112109. set.systems.push(system);
  112110. }
  112111. return set;
  112112. };
  112113. /**
  112114. * Gets or sets base Assets URL
  112115. */
  112116. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  112117. return ParticleHelper;
  112118. }());
  112119. BABYLON.ParticleHelper = ParticleHelper;
  112120. })(BABYLON || (BABYLON = {}));
  112121. //# sourceMappingURL=babylon.particleHelper.js.map
  112122. var BABYLON;
  112123. (function (BABYLON) {
  112124. /**
  112125. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  112126. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  112127. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  112128. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112129. */
  112130. var VideoDome = /** @class */ (function (_super) {
  112131. __extends(VideoDome, _super);
  112132. /**
  112133. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  112134. * @param name Element's name, child elements will append suffixes for their own names.
  112135. * @param urlsOrVideo defines the url(s) or the video element to use
  112136. * @param options An object containing optional or exposed sub element properties
  112137. */
  112138. function VideoDome(name, urlsOrVideo, options, scene) {
  112139. var _this = _super.call(this, name, scene) || this;
  112140. _this._useDirectMapping = false;
  112141. // set defaults and manage values
  112142. name = name || "videoDome";
  112143. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112144. options.clickToPlay = Boolean(options.clickToPlay);
  112145. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  112146. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  112147. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112148. if (options.useDirectMapping === undefined) {
  112149. _this._useDirectMapping = true;
  112150. }
  112151. else {
  112152. _this._useDirectMapping = options.useDirectMapping;
  112153. }
  112154. _this._setReady(false);
  112155. // create
  112156. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  112157. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112158. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  112159. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112160. texture.onLoadObservable.addOnce(function () {
  112161. _this._setReady(true);
  112162. });
  112163. // configure material
  112164. material.useEquirectangularFOV = true;
  112165. material.fovMultiplier = 1.0;
  112166. material.opacityFresnel = false;
  112167. if (_this._useDirectMapping) {
  112168. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112169. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112170. material.diffuseTexture = texture;
  112171. }
  112172. else {
  112173. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112174. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112175. material.reflectionTexture = texture;
  112176. }
  112177. // configure mesh
  112178. _this._mesh.material = material;
  112179. _this._mesh.parent = _this;
  112180. // optional configuration
  112181. if (options.clickToPlay) {
  112182. scene.onPointerUp = function () {
  112183. _this._videoTexture.video.play();
  112184. };
  112185. }
  112186. return _this;
  112187. }
  112188. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  112189. /**
  112190. * Gets the video texture being displayed on the sphere
  112191. */
  112192. get: function () {
  112193. return this._videoTexture;
  112194. },
  112195. enumerable: true,
  112196. configurable: true
  112197. });
  112198. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  112199. /**
  112200. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112201. * Also see the options.resolution property.
  112202. */
  112203. get: function () {
  112204. return this._material.fovMultiplier;
  112205. },
  112206. set: function (value) {
  112207. this._material.fovMultiplier = value;
  112208. },
  112209. enumerable: true,
  112210. configurable: true
  112211. });
  112212. /**
  112213. * Releases resources associated with this node.
  112214. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112215. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112216. */
  112217. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112218. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112219. this._videoTexture.dispose();
  112220. this._mesh.dispose();
  112221. this._material.dispose();
  112222. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112223. };
  112224. return VideoDome;
  112225. }(BABYLON.TransformNode));
  112226. BABYLON.VideoDome = VideoDome;
  112227. })(BABYLON || (BABYLON = {}));
  112228. //# sourceMappingURL=babylon.videoDome.js.map
  112229. var BABYLON;
  112230. (function (BABYLON) {
  112231. /**
  112232. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  112233. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  112234. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  112235. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112236. */
  112237. var PhotoDome = /** @class */ (function (_super) {
  112238. __extends(PhotoDome, _super);
  112239. /**
  112240. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  112241. * @param name Element's name, child elements will append suffixes for their own names.
  112242. * @param urlsOfPhoto defines the url of the photo to display
  112243. * @param options defines an object containing optional or exposed sub element properties
  112244. * @param onError defines a callback called when an error occured while loading the texture
  112245. */
  112246. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  112247. if (onError === void 0) { onError = null; }
  112248. var _this = _super.call(this, name, scene) || this;
  112249. _this._useDirectMapping = false;
  112250. /**
  112251. * Observable raised when an error occured while loading the 360 image
  112252. */
  112253. _this.onLoadErrorObservable = new BABYLON.Observable();
  112254. // set defaults and manage values
  112255. name = name || "photoDome";
  112256. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112257. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112258. if (options.useDirectMapping === undefined) {
  112259. _this._useDirectMapping = true;
  112260. }
  112261. else {
  112262. _this._useDirectMapping = options.useDirectMapping;
  112263. }
  112264. _this._setReady(false);
  112265. // create
  112266. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112267. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112268. // configure material
  112269. material.opacityFresnel = false;
  112270. material.useEquirectangularFOV = true;
  112271. material.fovMultiplier = 1.0;
  112272. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  112273. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  112274. if (onError) {
  112275. onError(message, exception);
  112276. }
  112277. });
  112278. _this.photoTexture.onLoadObservable.addOnce(function () {
  112279. _this._setReady(true);
  112280. });
  112281. // configure mesh
  112282. _this._mesh.material = material;
  112283. _this._mesh.parent = _this;
  112284. return _this;
  112285. }
  112286. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  112287. /**
  112288. * Gets or sets the texture being displayed on the sphere
  112289. */
  112290. get: function () {
  112291. return this._photoTexture;
  112292. },
  112293. set: function (value) {
  112294. if (this._photoTexture === value) {
  112295. return;
  112296. }
  112297. this._photoTexture = value;
  112298. if (this._useDirectMapping) {
  112299. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112300. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112301. this._material.diffuseTexture = this._photoTexture;
  112302. }
  112303. else {
  112304. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112305. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112306. this._material.reflectionTexture = this._photoTexture;
  112307. }
  112308. },
  112309. enumerable: true,
  112310. configurable: true
  112311. });
  112312. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  112313. /**
  112314. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112315. * Also see the options.resolution property.
  112316. */
  112317. get: function () {
  112318. return this._material.fovMultiplier;
  112319. },
  112320. set: function (value) {
  112321. this._material.fovMultiplier = value;
  112322. },
  112323. enumerable: true,
  112324. configurable: true
  112325. });
  112326. /**
  112327. * Releases resources associated with this node.
  112328. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112329. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112330. */
  112331. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112332. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112333. this._photoTexture.dispose();
  112334. this._mesh.dispose();
  112335. this._material.dispose();
  112336. this.onLoadErrorObservable.clear();
  112337. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112338. };
  112339. return PhotoDome;
  112340. }(BABYLON.TransformNode));
  112341. BABYLON.PhotoDome = PhotoDome;
  112342. })(BABYLON || (BABYLON = {}));
  112343. //# sourceMappingURL=babylon.photoDome.js.map
  112344. var BABYLON;
  112345. (function (BABYLON) {
  112346. BABYLON.Engine.prototype.createQuery = function () {
  112347. return this._gl.createQuery();
  112348. };
  112349. BABYLON.Engine.prototype.deleteQuery = function (query) {
  112350. this._gl.deleteQuery(query);
  112351. return this;
  112352. };
  112353. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  112354. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  112355. };
  112356. BABYLON.Engine.prototype.getQueryResult = function (query) {
  112357. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  112358. };
  112359. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  112360. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112361. this._gl.beginQuery(glAlgorithm, query);
  112362. return this;
  112363. };
  112364. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  112365. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112366. this._gl.endQuery(glAlgorithm);
  112367. return this;
  112368. };
  112369. BABYLON.Engine.prototype._createTimeQuery = function () {
  112370. var timerQuery = this.getCaps().timerQuery;
  112371. if (timerQuery.createQueryEXT) {
  112372. return timerQuery.createQueryEXT();
  112373. }
  112374. return this.createQuery();
  112375. };
  112376. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  112377. var timerQuery = this.getCaps().timerQuery;
  112378. if (timerQuery.deleteQueryEXT) {
  112379. timerQuery.deleteQueryEXT(query);
  112380. return;
  112381. }
  112382. this.deleteQuery(query);
  112383. };
  112384. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  112385. var timerQuery = this.getCaps().timerQuery;
  112386. if (timerQuery.getQueryObjectEXT) {
  112387. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  112388. }
  112389. return this.getQueryResult(query);
  112390. };
  112391. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  112392. var timerQuery = this.getCaps().timerQuery;
  112393. if (timerQuery.getQueryObjectEXT) {
  112394. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  112395. }
  112396. return this.isQueryResultAvailable(query);
  112397. };
  112398. BABYLON.Engine.prototype.startTimeQuery = function () {
  112399. var caps = this.getCaps();
  112400. var timerQuery = caps.timerQuery;
  112401. if (!timerQuery) {
  112402. return null;
  112403. }
  112404. var token = new BABYLON._TimeToken();
  112405. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112406. if (caps.canUseTimestampForTimerQuery) {
  112407. token._startTimeQuery = this._createTimeQuery();
  112408. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  112409. }
  112410. else {
  112411. if (this._currentNonTimestampToken) {
  112412. return this._currentNonTimestampToken;
  112413. }
  112414. token._timeElapsedQuery = this._createTimeQuery();
  112415. if (timerQuery.beginQueryEXT) {
  112416. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112417. }
  112418. else {
  112419. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112420. }
  112421. this._currentNonTimestampToken = token;
  112422. }
  112423. return token;
  112424. };
  112425. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  112426. var caps = this.getCaps();
  112427. var timerQuery = caps.timerQuery;
  112428. if (!timerQuery || !token) {
  112429. return -1;
  112430. }
  112431. if (caps.canUseTimestampForTimerQuery) {
  112432. if (!token._startTimeQuery) {
  112433. return -1;
  112434. }
  112435. if (!token._endTimeQuery) {
  112436. token._endTimeQuery = this._createTimeQuery();
  112437. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  112438. }
  112439. }
  112440. else if (!token._timeElapsedQueryEnded) {
  112441. if (!token._timeElapsedQuery) {
  112442. return -1;
  112443. }
  112444. if (timerQuery.endQueryEXT) {
  112445. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  112446. }
  112447. else {
  112448. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  112449. }
  112450. token._timeElapsedQueryEnded = true;
  112451. }
  112452. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112453. var available = false;
  112454. if (token._endTimeQuery) {
  112455. available = this._getTimeQueryAvailability(token._endTimeQuery);
  112456. }
  112457. else if (token._timeElapsedQuery) {
  112458. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  112459. }
  112460. if (available && !disjoint) {
  112461. var result = 0;
  112462. if (caps.canUseTimestampForTimerQuery) {
  112463. if (!token._startTimeQuery || !token._endTimeQuery) {
  112464. return -1;
  112465. }
  112466. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  112467. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  112468. result = timeEnd - timeStart;
  112469. this._deleteTimeQuery(token._startTimeQuery);
  112470. this._deleteTimeQuery(token._endTimeQuery);
  112471. token._startTimeQuery = null;
  112472. token._endTimeQuery = null;
  112473. }
  112474. else {
  112475. if (!token._timeElapsedQuery) {
  112476. return -1;
  112477. }
  112478. result = this._getTimeQueryResult(token._timeElapsedQuery);
  112479. this._deleteTimeQuery(token._timeElapsedQuery);
  112480. token._timeElapsedQuery = null;
  112481. token._timeElapsedQueryEnded = false;
  112482. this._currentNonTimestampToken = null;
  112483. }
  112484. return result;
  112485. }
  112486. return -1;
  112487. };
  112488. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  112489. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  112490. };
  112491. // We also need to update AbstractMesh as there is a portion of the code there
  112492. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  112493. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  112494. this._isOccluded = false;
  112495. return;
  112496. }
  112497. var engine = this.getEngine();
  112498. if (engine.webGLVersion < 2) {
  112499. this._isOccluded = false;
  112500. return;
  112501. }
  112502. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  112503. this._isOccluded = false;
  112504. return;
  112505. }
  112506. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  112507. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  112508. if (isOcclusionQueryAvailable) {
  112509. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  112510. this._isOcclusionQueryInProgress = false;
  112511. this._occlusionInternalRetryCounter = 0;
  112512. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  112513. }
  112514. else {
  112515. this._occlusionInternalRetryCounter++;
  112516. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  112517. this._isOcclusionQueryInProgress = false;
  112518. this._occlusionInternalRetryCounter = 0;
  112519. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  112520. // if strict continue the last state of the object.
  112521. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  112522. }
  112523. else {
  112524. return;
  112525. }
  112526. }
  112527. }
  112528. var scene = this.getScene();
  112529. if (scene.getBoundingBoxRenderer) {
  112530. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  112531. if (!this._occlusionQuery) {
  112532. this._occlusionQuery = engine.createQuery();
  112533. }
  112534. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  112535. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  112536. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  112537. this._isOcclusionQueryInProgress = true;
  112538. }
  112539. };
  112540. })(BABYLON || (BABYLON = {}));
  112541. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  112542. var BABYLON;
  112543. (function (BABYLON) {
  112544. /**
  112545. * Class used to generate noise procedural textures
  112546. */
  112547. var NoiseProceduralTexture = /** @class */ (function (_super) {
  112548. __extends(NoiseProceduralTexture, _super);
  112549. /**
  112550. * Creates a new NoiseProceduralTexture
  112551. * @param name defines the name fo the texture
  112552. * @param size defines the size of the texture (default is 256)
  112553. * @param scene defines the hosting scene
  112554. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  112555. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  112556. */
  112557. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  112558. if (size === void 0) { size = 256; }
  112559. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  112560. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  112561. _this._time = 0;
  112562. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  112563. _this.brightness = 0.2;
  112564. /** Defines the number of octaves to process */
  112565. _this.octaves = 3;
  112566. /** Defines the level of persistence (0.8 by default) */
  112567. _this.persistence = 0.8;
  112568. /** Gets or sets animation speed factor (default is 1) */
  112569. _this.animationSpeedFactor = 1;
  112570. _this._updateShaderUniforms();
  112571. return _this;
  112572. }
  112573. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  112574. var scene = this.getScene();
  112575. if (!scene) {
  112576. return;
  112577. }
  112578. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  112579. this.setFloat("brightness", this.brightness);
  112580. this.setFloat("persistence", this.persistence);
  112581. this.setFloat("timeScale", this._time);
  112582. };
  112583. NoiseProceduralTexture.prototype._getDefines = function () {
  112584. return "#define OCTAVES " + (this.octaves | 0);
  112585. };
  112586. /** Generate the current state of the procedural texture */
  112587. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  112588. this._updateShaderUniforms();
  112589. _super.prototype.render.call(this, useCameraPostProcess);
  112590. };
  112591. /**
  112592. * Serializes this noise procedural texture
  112593. * @returns a serialized noise procedural texture object
  112594. */
  112595. NoiseProceduralTexture.prototype.serialize = function () {
  112596. var serializationObject = {};
  112597. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  112598. serializationObject.brightness = this.brightness;
  112599. serializationObject.octaves = this.octaves;
  112600. serializationObject.persistence = this.persistence;
  112601. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  112602. serializationObject.size = this.getSize().width;
  112603. serializationObject.generateMipMaps = this._generateMipMaps;
  112604. return serializationObject;
  112605. };
  112606. /**
  112607. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  112608. * @param parsedTexture defines parsed texture data
  112609. * @param scene defines the current scene
  112610. * @param rootUrl defines the root URL containing noise procedural texture information
  112611. * @returns a parsed NoiseProceduralTexture
  112612. */
  112613. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  112614. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  112615. texture.brightness = parsedTexture.brightness;
  112616. texture.octaves = parsedTexture.octaves;
  112617. texture.persistence = parsedTexture.persistence;
  112618. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  112619. return texture;
  112620. };
  112621. return NoiseProceduralTexture;
  112622. }(BABYLON.ProceduralTexture));
  112623. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  112624. })(BABYLON || (BABYLON = {}));
  112625. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  112626. var __assign = (this && this.__assign) || function () {
  112627. __assign = Object.assign || function(t) {
  112628. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112629. s = arguments[i];
  112630. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112631. t[p] = s[p];
  112632. }
  112633. return t;
  112634. };
  112635. return __assign.apply(this, arguments);
  112636. };
  112637. var BABYLON;
  112638. (function (BABYLON) {
  112639. /**
  112640. * This can helps recording videos from BabylonJS.
  112641. * This is based on the available WebRTC functionalities of the browser.
  112642. *
  112643. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  112644. */
  112645. var VideoRecorder = /** @class */ (function () {
  112646. /**
  112647. * Create a new VideoCapture object which can help converting what you see in Babylon to
  112648. * a video file.
  112649. * @param engine Defines the BabylonJS Engine you wish to record
  112650. * @param options Defines options that can be used to customized the capture
  112651. */
  112652. function VideoRecorder(engine, options) {
  112653. if (options === void 0) { options = null; }
  112654. if (!VideoRecorder.IsSupported(engine)) {
  112655. throw "Your browser does not support recording so far.";
  112656. }
  112657. var canvas = engine.getRenderingCanvas();
  112658. if (!canvas) {
  112659. throw "The babylon engine must have a canvas to be recorded";
  112660. }
  112661. this._canvas = canvas;
  112662. this._canvas.isRecording = false;
  112663. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  112664. var stream = this._canvas.captureStream(this._options.fps);
  112665. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  112666. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  112667. this._mediaRecorder.onerror = this._handleError.bind(this);
  112668. this._mediaRecorder.onstop = this._handleStop.bind(this);
  112669. }
  112670. /**
  112671. * Returns wehther or not the VideoRecorder is available in your browser.
  112672. * @param engine Defines the Babylon Engine to check the support for
  112673. * @returns true if supported otherwise false
  112674. */
  112675. VideoRecorder.IsSupported = function (engine) {
  112676. var canvas = engine.getRenderingCanvas();
  112677. return (!!canvas && typeof canvas.captureStream === "function");
  112678. };
  112679. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  112680. /**
  112681. * True wether a recording is already in progress.
  112682. */
  112683. get: function () {
  112684. return !!this._canvas && this._canvas.isRecording;
  112685. },
  112686. enumerable: true,
  112687. configurable: true
  112688. });
  112689. /**
  112690. * Stops the current recording before the default capture timeout passed in the startRecording
  112691. * functions.
  112692. */
  112693. VideoRecorder.prototype.stopRecording = function () {
  112694. if (!this._canvas || !this._mediaRecorder) {
  112695. return;
  112696. }
  112697. if (!this.isRecording) {
  112698. return;
  112699. }
  112700. this._canvas.isRecording = false;
  112701. this._mediaRecorder.stop();
  112702. };
  112703. /**
  112704. * Starts recording the canvas for a max duration specified in parameters.
  112705. * @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.
  112706. * @param maxDuration Defines the maximum recording time in seconds.
  112707. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  112708. * @return a promise callback at the end of the recording with the video data in Blob.
  112709. */
  112710. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  112711. var _this = this;
  112712. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  112713. if (maxDuration === void 0) { maxDuration = 7; }
  112714. if (!this._canvas || !this._mediaRecorder) {
  112715. throw "Recorder has already been disposed";
  112716. }
  112717. if (this.isRecording) {
  112718. throw "Recording already in progress";
  112719. }
  112720. if (maxDuration > 0) {
  112721. setTimeout(function () {
  112722. _this.stopRecording();
  112723. }, maxDuration * 1000);
  112724. }
  112725. this._fileName = fileName;
  112726. this._recordedChunks = [];
  112727. this._resolve = null;
  112728. this._reject = null;
  112729. this._canvas.isRecording = true;
  112730. this._mediaRecorder.start(this._options.recordChunckSize);
  112731. return new Promise(function (resolve, reject) {
  112732. _this._resolve = resolve;
  112733. _this._reject = reject;
  112734. });
  112735. };
  112736. /**
  112737. * Releases internal resources used during the recording.
  112738. */
  112739. VideoRecorder.prototype.dispose = function () {
  112740. this._canvas = null;
  112741. this._mediaRecorder = null;
  112742. this._recordedChunks = [];
  112743. this._fileName = null;
  112744. this._resolve = null;
  112745. this._reject = null;
  112746. };
  112747. VideoRecorder.prototype._handleDataAvailable = function (event) {
  112748. if (event.data.size > 0) {
  112749. this._recordedChunks.push(event.data);
  112750. }
  112751. };
  112752. VideoRecorder.prototype._handleError = function (event) {
  112753. this.stopRecording();
  112754. if (this._reject) {
  112755. this._reject(event.error);
  112756. }
  112757. else {
  112758. throw new event.error;
  112759. }
  112760. };
  112761. VideoRecorder.prototype._handleStop = function () {
  112762. this.stopRecording();
  112763. var superBuffer = new Blob(this._recordedChunks);
  112764. if (this._resolve) {
  112765. this._resolve(superBuffer);
  112766. }
  112767. window.URL.createObjectURL(superBuffer);
  112768. if (this._fileName) {
  112769. BABYLON.Tools.Download(superBuffer, this._fileName);
  112770. }
  112771. };
  112772. VideoRecorder._defaultOptions = {
  112773. mimeType: "video/webm",
  112774. fps: 25,
  112775. recordChunckSize: 3000
  112776. };
  112777. return VideoRecorder;
  112778. }());
  112779. BABYLON.VideoRecorder = VideoRecorder;
  112780. })(BABYLON || (BABYLON = {}));
  112781. //# sourceMappingURL=babylon.videoRecorder.js.map
  112782. var BABYLON;
  112783. (function (BABYLON) {
  112784. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  112785. if (replace === void 0) { replace = false; }
  112786. // Dispose existing light in replace mode.
  112787. if (replace) {
  112788. if (this.lights) {
  112789. for (var i = 0; i < this.lights.length; i++) {
  112790. this.lights[i].dispose();
  112791. }
  112792. }
  112793. }
  112794. // Light
  112795. if (this.lights.length === 0) {
  112796. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  112797. }
  112798. };
  112799. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  112800. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112801. if (replace === void 0) { replace = false; }
  112802. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112803. // Dispose existing camera in replace mode.
  112804. if (replace) {
  112805. if (this.activeCamera) {
  112806. this.activeCamera.dispose();
  112807. this.activeCamera = null;
  112808. }
  112809. }
  112810. // Camera
  112811. if (!this.activeCamera) {
  112812. var worldExtends = this.getWorldExtends();
  112813. var worldSize = worldExtends.max.subtract(worldExtends.min);
  112814. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  112815. var camera;
  112816. var radius = worldSize.length() * 1.5;
  112817. // empty scene scenario!
  112818. if (!isFinite(radius)) {
  112819. radius = 1;
  112820. worldCenter.copyFromFloats(0, 0, 0);
  112821. }
  112822. if (createArcRotateCamera) {
  112823. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  112824. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  112825. arcRotateCamera.wheelPrecision = 100 / radius;
  112826. camera = arcRotateCamera;
  112827. }
  112828. else {
  112829. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  112830. freeCamera.setTarget(worldCenter);
  112831. camera = freeCamera;
  112832. }
  112833. camera.minZ = radius * 0.01;
  112834. camera.maxZ = radius * 1000;
  112835. camera.speed = radius * 0.2;
  112836. this.activeCamera = camera;
  112837. var canvas = this.getEngine().getRenderingCanvas();
  112838. if (attachCameraControls && canvas) {
  112839. camera.attachControl(canvas);
  112840. }
  112841. }
  112842. };
  112843. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  112844. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112845. if (replace === void 0) { replace = false; }
  112846. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112847. this.createDefaultLight(replace);
  112848. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  112849. };
  112850. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  112851. if (pbr === void 0) { pbr = false; }
  112852. if (scale === void 0) { scale = 1000; }
  112853. if (blur === void 0) { blur = 0; }
  112854. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  112855. if (!environmentTexture) {
  112856. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  112857. return null;
  112858. }
  112859. if (setGlobalEnvTexture) {
  112860. if (environmentTexture) {
  112861. this.environmentTexture = environmentTexture;
  112862. }
  112863. }
  112864. // Skybox
  112865. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  112866. if (pbr) {
  112867. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  112868. hdrSkyboxMaterial.backFaceCulling = false;
  112869. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  112870. if (hdrSkyboxMaterial.reflectionTexture) {
  112871. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112872. }
  112873. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  112874. hdrSkyboxMaterial.disableLighting = true;
  112875. hdrSkyboxMaterial.twoSidedLighting = true;
  112876. hdrSkybox.infiniteDistance = true;
  112877. hdrSkybox.material = hdrSkyboxMaterial;
  112878. }
  112879. else {
  112880. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  112881. skyboxMaterial.backFaceCulling = false;
  112882. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  112883. if (skyboxMaterial.reflectionTexture) {
  112884. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112885. }
  112886. skyboxMaterial.disableLighting = true;
  112887. hdrSkybox.infiniteDistance = true;
  112888. hdrSkybox.material = skyboxMaterial;
  112889. }
  112890. return hdrSkybox;
  112891. };
  112892. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  112893. if (BABYLON.EnvironmentHelper) {
  112894. return new BABYLON.EnvironmentHelper(options, this);
  112895. }
  112896. return null;
  112897. };
  112898. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  112899. if (webVROptions === void 0) { webVROptions = {}; }
  112900. return new BABYLON.VRExperienceHelper(this, webVROptions);
  112901. };
  112902. })(BABYLON || (BABYLON = {}));
  112903. //# sourceMappingURL=babylon.sceneHelpers.js.map
  112904. 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"};
  112905. 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};"};